سؤال

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