How to Get XML Node from XDocument
Asked Answered
S

2

35

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? I want to update some values in that node.

How can this be done?

Selfeducated answered 15/4, 2009 at 15:34 Comment(0)
K
72

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");
Kimmi answered 28/5, 2010 at 14:31 Comment(1)
The link is dead.Revalue
S
12

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

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

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

Slumgullion answered 15/4, 2009 at 16:1 Comment(3)
Your edit made it clear. He is falling prey to the classic mistake of trying to use the query as the result set. https://mcmap.net/q/428837/-a-question-about-linq-to-sql/… My answer to a similar questionAbbacy
Hi, Thanks for the response. But I am still getting the error....... Through this query, how can I add new nodes, update and delete node in an XDocument ????Selfeducated
If you want to add new elements, you need to grab the XElement you want to add something to. What do you want to do? You can't do all through one single query...Slumgullion

© 2022 - 2024 — McMap. All rights reserved.