How to Get XML Node from XDocument

Shine S picture Shine S · Apr 15, 2009 · Viewed 124.2k times · Source

How to Get an XML Element from XDocument using LINQ ?

Suppose I have an XDocument Named XMLDoc which is shown below:

<Contacts>
       <Node>
           <ID>123</ID>
           <Name>ABC</Name>
       </Node>
       <Node>
           <ID>124</ID>
           <Name>DEF</Name>
       </Node>
</Contacts>

XElement Contacts = from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2;

But I am getting Error "Object Reference is NOT to set....."

How to get a particular Node from a XML file using LINQ ? And I want to update some values in that node ?

How it is possible ????

Thanks in advance.........

Answer

Ondrej Slint&#225;k picture Ondrej Slinták · May 28, 2010

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Node>
    <ID>123</ID>
    <Name>ABC</Name>
  </Node>
  <Node>
    <ID>124</ID>
    <Name>DEF</Name>
  </Node>
</Contacts>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

Console.WriteLine(Contact.ToString());

Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();

Contact.Remove();
XMLDoc.Save("test.xml");

Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")
);

XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");