LINQ Xelement Returns null when a child node exists

I have an XML file like this and I want to read the value of ID, shortname, Name node.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <AccountingUnitList xmlns="http://www.google.com"> <AccountingUnit> <ID>17406</ID> <ShortName>test</ShortName> <Name>test</Name> </AccountingUnit> <AccountingUnit> <ID>18006</ID> <ShortName>ANOTHERtest</ShortName> <Name>Anothertest</Name> </AccountingUnit> <AccountingUnit> <ID>18046</ID> <ShortName>RKU</ShortName> <Name>hospital</Name> </AccountingUnit> <AccountingUnit> <ID>18047</ID> <ShortName>MNU</ShortName> <Name>MNU</Name> </AccountingUnit> </AccountingUnitList> 

what is the best way to read a node element recursively?

This is how I try to read the value of node:

 var accountingunit = ( from e in XDocument.Parse(textresult).Root.Elements("AccountingUnit") select new node { idvalue = (string)e.Element("ID"), shortname =(string)e.Element("ShortName"), name = (string)e.Element("Name"), }); foreach(var unit in accountingunit) { Console.WriteLine("ID"+ unit.idvalue + unit.name + unit.shortname); } 

Here is the node constructor:

 public class node { public string idvalue { get; set; } public string shortname { get; set; } public string name { get; set; } } 
+6
source share
1 answer

You have an xml namespace in your document. All children of AccountingUnitList inherit a namespace, so you need to specify it through the element name:

 XNamespace ns = "http://www.google.com"; var accountingunit = ( from e in XDocument.Parse(textresult).Elements(ns + "AccountingUnit") select new node { idvalue = (string)e.Element(ns + "ID"), shortname =(string)e.Element(ns + "ShortName"), name = (string)e.Element(ns + "Name"), }); 
+11
source

Source: https://habr.com/ru/post/978989/


All Articles