【问题标题】:Writing and then removing node from XML doc using C#/Unity3D使用 C#/Unity3D 从 XML 文档中写入然后删除节点
【发布时间】: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 坐标。
  • 出了什么问题?如果我使用您的代码和测试文档来添加,然后一个接一个地删除相同的节点,它对我有用。

标签: c# .net xml unity3d


【解决方案1】:

如果您不打算使用 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);
}

【讨论】:

  • 在使用 .Where() 方法和“from”关键字时遇到问题。我已经添加了库和扩展。
  • 应该是 in 而不是 from - 我的错误。 Where 对我来说编译得很好。您确实在文件顶部放置了 using XmlLib; 以及其他使用,或者将命名空间更改为与您的文件相同?您不能剪掉 Get() 方法并将其放在同一个类中。扩展方法必须在静态类中。
猜你喜欢
  • 2016-11-05
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 2016-06-23
  • 2022-11-02
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多