2012-03-02 126 views
0

我正在嘗試將節點添加到xml文檔,然後刪除它們。 添加節點正在工作,但我不能刪除節點,除非我重新啓動程序。使用C#/ Unity3D編寫XML文檔然後刪除節點

Write方法:

public void writeToExistingDoc (String fileNamePath, int x, int y, int t) 
{ 
    string filename = fileNamePath; 
    string xPos = "" + x; 
    string yPos = "" + y; 
    string type = "" + t; 

    //create new instance of XmlDocument 
    XmlDocument doc = new XmlDocument(); 

    //load from file 
    doc.Load (filename); 

    //create node and add value 
    XmlNode node = doc.CreateNode (XmlNodeType.Element, "BUILDING", null); 

    XmlAttribute atr = doc.CreateAttribute ("x"); 
    XmlAttribute atr2 = doc.CreateAttribute ("y"); 
    XmlAttribute atr3 = doc.CreateAttribute ("type"); 
    atr.Value = xPos; 
    atr2.Value = yPos; 
    atr3.Value = type; 
    node.Attributes.Append (atr); 
    node.Attributes.Append (atr2); 
    node.Attributes.Append (atr3); 



    //add to elements collection 
    doc.DocumentElement.AppendChild (node); 

    Debug.Log ("Element added"); 
    //save back 
    doc.Save (filename); 

} 

,這裏是刪除方法:

public void removeBuildingNode (string fileNamePath, int buildingPosX, int buildingPosY) 
{ 
    XmlDocument doc = new XmlDocument(); 
    doc.Load (fileNamePath); 
    XmlNodeList nodes = doc.SelectNodes ("//BUILDING[@x='" + buildingPosX + "']"); 
    for (int i = nodes.Count - 1; i >= 0; i--) { 
     Debug.Log("" + i); 
     nodes[i].ParentNode.RemoveChild (nodes[i]); 
    } 
    doc.Save(fileNamePath); 
    Debug.Log(""+buildingPosX + ", " + buildingPosY); 


} 

我的XML文檔看起來是這樣的:

<BUILDINGS ID="b"> 
<BUILDING x="50" y="80" type="1" /> 
<BUILDING x="25" y="125" type="1" /> 
<BUILDING x="35" y="125" type="1" /> 
<BUILDING x="45" y="125" type="1" /> 
</BUILDINGS> 

正如我所說,方法,當我第一次運行程序時,使用寫入方法,重新啓動程序並使用remove方法。不會在相同的運行實例上工作。

+0

順便說一句,我只是使用的x座標現在。 – Hassel 2012-03-02 19:12:10

+0

出了什麼問題?如果我使用你的代碼和測試文檔來添加,然後一個接一個地刪除同一個節點,它對我有用。 – 2012-03-02 22:30:13

回答

0

如果你不使用XmlDocument的彎曲,這應該工作...

使用:http://searisen.com/xmllib/extensions.wiki

public void removeBuildingNode (string fileNamePath, int buildingPosX, int buildingPosY) 
{ 
    XElement doc = XElement.Load(fileNamePath); 
    var nodesToRemove = doc.Elements("BUILDING") 
     .Where(xe => xe.Get("x", int.MinValue) == buildingPosX); 

    foreach(XElement node in nodesToRemove.ToArray()) 
     node.Remove(); 

    doc.Save(fileNamePath); 

    Debug.Log(""+buildingPosX + ", " + buildingPosY); 
} 
+0

無法使用.Where()方法和「from」關鍵字。我添加了庫和擴展。 – Hassel 2012-03-03 00:01:39

+0

應該是'in'而不是'from' - 我的錯誤。 「Where」編譯對我來說很好。你確實在你的其他使用文件的頂部放了一個'使用XmlLib;'或者把命名空間改爲和你的文件一樣?你不能修剪Get()方法並把它放在同一個類中。擴展方法必須處於靜態類中。 – 2012-03-03 00:52:42