0

I'm trying to find existing content within an XML file and change it by making use of the SelectSingleNode command. However, all I get is a NullReferenceException. Maybe I'm just not getting how the file path works with this particular command, but I've tried many variants I've found online but to no avail. Could anyone help me figure out what I'm doing wrong?

Here's the script.

public void saveStuff()
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(@"Worlds\WorldData.xml"); //loads the file just fine

    XmlNode node = xmlDoc.SelectSingleNode("//World[@ID='002']/Name"); //node = null
    node.Value = "New Name"; //NullReferenceException was unhandled
    xmlDoc.Save(@"Worlds\example.xml");
}

And here's a sample of my XML file.

<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
  <World ID="001">
    <Name>
      TinyWorld
    </Name>
    <Size>
      4x4
    </Size>
    <Tiles>
      000,000,000,001,
      000,000,000,001,
      001,001,004,001,
      001,001,001,001,
    </Tiles>
  </World>
  <World ID="002">
    <Name>
      MicroWorld
    </Name>
    <Size>
       2x2
    </Size>
    <Tiles>
      000,000,
      001,001,
     </Tiles>
  </World>
</XnaContent>
4

1 回答 1

0

反而:

public void saveStuff()
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(@"Worlds\WorldData.xml");

    XmlElement root = xmlDoc.DocumentElement;
    XmlNode node = root.SelectSingleNode("//World[@ID='002']/Name");
    node.Value = "New Name";
    xmlDoc.Save(@"Worlds\example.xml");
}

您正在选择使用//xpath,但当时没有上下文。该语法是相对于当前节点的。

于 2013-06-06T18:37:37.337 回答