Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of child node from XDocument

Tags:

c#

xml

linq

I need to get value of child node from XDocument using linq

<root>
<Cust>
     <ACTNumber>1234</ACTNumber>
     <Address>
         <Street></Street>
         <City>123 Main street</City>
         <State>AL</State>
     </Address>
</Cust>
</root>

I tried this: xDocTest.Root.Elements("Cust").Elements("ACTNumber")

If I try Address instead of ACTNumber then it works. But its not giving the child node value.

like image 387
user1532976 Avatar asked Apr 25 '13 17:04

user1532976


2 Answers

If there's only one Cust element and only one ACTNumber element, then it's easy:

string actNumber = doc.Root.Element("Cust").Element("ACTNumber").Value;

Or to get it as a long:

long actNumber = (long) doc.Root.Element("Cust").Element("ACTNumber");
like image 190
Jon Skeet Avatar answered Nov 15 '22 12:11

Jon Skeet


Use this:

xDocTest.Root.Element("Cust").Element("Adress").Element("City").Value

If you use Elements (note the plural) it gives u an IEnumerable, this would be used like this:

XML

<Father>
    <Child>Hello</Child>
    <Child>World!</Child>
</Father>

C#

foreach(var childElement in Root.Elements("Child")) Console.WriteLine(childElement.Value);

Or to take your example:

foreach(var child in xdoc.Root.Element("Cust").Element("Address").Elements()) 
    Console.WriteLine(string.Format("{0} : {1}", child.Name, child.Value);

Im not sure how Element behaves if you have multiple Elements of the same name. So you might want to use Elements and Inerate over all occurences.

And in Linq If there is more than one Customer...

var result = from cust in xdoc.Root.Elements("Cust")

             where cust.Elements("ACTNumber").Any() // This is to make sure there
                                                    // is an element called ACTNumber
                                                    // otherwise .Value would create
                                                    // Nullrefexception.

             select child.Element("ACTNumber").Value;
like image 34
CSharpie Avatar answered Nov 15 '22 13:11

CSharpie