Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Xelement Returns null when child node exist

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

<?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 the Node element recursively?

This is how I am trying to read the Node value:

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 consructor:

public class node
{
    public string idvalue { get; set; }
    public string shortname { get; set; }
    public string name { get; set; }
}
like image 747
user1514428 Avatar asked Dec 02 '14 11:12

user1514428


1 Answers

You have an xml namespace in your document.All the child elements of AccountingUnitList inherits the namespace so you need to specify it via 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"),

            });
like image 131
Selman Genç Avatar answered Nov 08 '22 20:11

Selman Genç