【问题标题】:Editing an XML file in C#; SelectSingleNode returns null在 C# 中编辑 XML 文件; SelectSingleNode 返回 null
【发布时间】:2013-06-06 18:24:38
【问题描述】:

我正在尝试在 XML 文件中查找现有内容并通过使用 SelectSingleNode 命令对其进行更改。但是,我得到的只是 NullReferenceException。也许我只是不知道文件路径如何与这个特定的命令一起工作,但我尝试了许多我在网上找到的变体,但无济于事。谁能帮我弄清楚我做错了什么?

这是脚本。

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

这是我的 XML 文件的示例。

<?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>

【问题讨论】:

    标签: c# xml xna-4.0 nullreferenceexception selectsinglenode


    【解决方案1】:

    改为:

    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 进行选择,但此时没有上下文。该语法与当前节点有关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-05
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      相关资源
      最近更新 更多