【问题标题】:Adding node to existing xml element将节点添加到现有 xml 元素
【发布时间】:2014-01-10 14:26:54
【问题描述】:

尝试将节点附加到我的 xml 文档中的现有元素时出现此错误。错误是:对象引用未设置为对象的实例。

<houses>
  <house windowsc="three">
    <wind>0</wind>
    <windows>
    </windows>
  </house>
</houses>

代码:

XmlDocument xDoc = new XmlDocument();

xDoc.Load("C:\\Houseplans.xml");

XmlElement xhousing = xDoc.DocumentElement["houses/house[@windowsc=\"three\"]/windows"];
XmlNode xName = xDoc.CreateElement("Name");
xName.InnerText = "hi";
xhousing.AppendChild(xName);

【问题讨论】:

  • 调试器说了什么?
  • 你可以使用 LINQ to XML 吗?
  • 发生了“System.NullReferenceException”类型的异常附加信息:对象引用未设置为对象的实例。
  • 你的xhousing is null,你的xpath没有得到节点
  • @Josh 看起来像 xhousingnull

标签: c# xml nullreferenceexception


【解决方案1】:

你想使用 SelectSingleNode:

XmlNode xhousing = xDoc.SelectSingleNode(@"//house[@windowsc='three']/windows");
XmlNode xName = xDoc.CreateElement("Name");
xName.InnerText = "hi";
xhousing.AppendChild(xName);

【讨论】:

  • 请注意 //house 与 /houses/house 不同。
猜你喜欢
  • 2020-10-28
  • 1970-01-01
  • 2012-11-27
  • 2013-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
相关资源
最近更新 更多