Rick
Rick

Reputation: 13

NullRefernceException when adding XElement to a XDocument

I have the following .xml file:

<?xml version="1.0" encoding="utf-8" ?>
<Params>
  <Name>Resolver1</Name>
  <RemoteHosts>
    <Host>
      <Name>Locale</Name>
       <IP>localhost</IP>
       <Port>8082</Port>
     </Host>
  </RemoteHosts>
</Params>

Now, when I try to add another "Host" in the "RemoteHosts" section using the following code it raises a NullReferenceException:

XDocument xmlList = XDocument.Load("NetConfig.xml");

xmlList.Element("RemoteHosts").Add(new XElement("Host",    
new XElement("Name", h.name),
new XElement("IP", h.IP),
new XElement("Port", h.port)));

anyway the

xmlList.Save("NetConfig.xml");

works well, saving the new item...what's wrong?

Upvotes: 0

Views: 285

Answers (2)

Shurdoof
Shurdoof

Reputation: 1719

Try xmlList.Root.Element("RemoteHosts")

Upvotes: 0

Piotr Auguscik
Piotr Auguscik

Reputation: 3681

XmlList contains only 1 node and its Params not RemoteHosts

Upvotes: 1

Related Questions