0

I'm getting this error when trying to append a node to existing element in my xml document.The error is: Object reference not set to an instance of an object.

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

Code:

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);
5
  • 1
    What did the debugger say? Commented Jan 10, 2014 at 14:29
  • Can you use LINQ to XML? Commented Jan 10, 2014 at 14:32
  • An exception of type 'System.NullReferenceException' occurred Additional information: Object reference not set to an instance of an object. Commented Jan 10, 2014 at 14:32
  • your xhousing is null, your xpath isn't getting the node Commented Jan 10, 2014 at 14:32
  • @Josh looks like xhousing is null Commented Jan 10, 2014 at 14:32

1 Answer 1

2

You want to use SelectSingleNode:

XmlNode xhousing = xDoc.SelectSingleNode(@"//house[@windowsc='three']/windows");
XmlNode xName = xDoc.CreateElement("Name");
xName.InnerText = "hi";
xhousing.AppendChild(xName);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that //house is different to /houses/house.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.