将节点添加到现有xml元素

时间:2014-01-10 14:26:55

标签: c# xml nullreferenceexception

尝试将节点附加到我的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);

1 个答案:

答案 0 :(得分:2)

您想使用SelectSingleNode:

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