简体   繁体   English

LINQ Xelement当子节点存在时返回null

[英]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文件,我想读取ID,短名称,名称节点值。

<?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? 递归读取Node元素的最佳方法是什么?

This is how I am trying to read the Node value: 这就是我尝试读取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 consructor: 这是节点consructor:

public class node
{
    public string idvalue { get; set; }
    public string shortname { get; set; }
    public string name { get; set; }
}

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: 你在你的document.all XML命名空间的子元素AccountingUnitList继承了命名空间,所以你需要通过元素名称来指定它:

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"),

            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM