2014-01-10 49 views
0

當我嘗試將節點附加到我的xml文檔中的現有元素時出現此錯誤。錯誤是:對象引用未設置爲對象的實例。將節點添加到現有的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

你可以使用LINQ to XML嗎? –

+0

發生類型爲'System.NullReferenceException'的異常 附加信息:未將對象引用設置爲對象的實例。 – Josh

回答

1

您想使用的SelectSingleNode:

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

yup thats correct。謝謝瓊斯。 – Josh

+1

請注意,//房屋不同於/ houses/house。 –

相關問題