문제

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>
도움이 되었습니까?

해결책

Instead:

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");
}

You were selecting using the // xpath, but at that moment, no context. That syntax is relative to the current node.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top