簡體   English   中英

LINQ Xelement當子節點存在時返回null

[英]LINQ Xelement Returns null when child node exist

我有一個像這樣的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>

遞歸讀取Node元素的最佳方法是什么?

這就是我嘗試讀取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);
            }

這是節點consructor:

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

你在你的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