【发布时间】:2012-03-02 19:09:59
【问题描述】:
我正在尝试将节点添加到 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);
}
这里是 Remove 方法:
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>
正如我所说,这些方法在我第一次运行程序时起作用,使用 write 方法,重新启动程序并使用 remove 方法。不能在同一个正在运行的实例上工作。
【问题讨论】:
-
顺便说一句,我现在只使用 x 坐标。
-
出了什么问题?如果我使用您的代码和测试文档来添加,然后一个接一个地删除相同的节点,它对我有用。