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.
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");
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With