开发者

Use LINQ to read all nodes from XML

开发者 https://www.devze.com 2023-01-19 02:48 出处:网络
I have a XML file, like this: <?xml version=\"1.0\" encoding=\"utf-8\" ?> <ROOT> <NAME>

I have a XML file, like this:

<?xml version="1.0" encoding="utf-8" ?>
<ROOT>
    <NAME>
        ItemName
    </NAME>
    <LIST>
       <ITEM>
          ListItem1
       </ITEM> 
       <ITEM>
 开发者_如何学C         ListItem2
       </ITEM> 
       <ITEM>
          ListItem3
       </ITEM> 
    </LIST>
</ROOT>

How can I use LINQ to get all the ITEMs inside the LIST tag?


Something like:

XDocument doc = XDocument.Load("foo.xml");
var items = from list in doc.Descendants("LIST")
            from item in list.Elements("ITEM")
            select item;

That will cope with multiple "LIST" elements, and won't find "ITEM" elements except directly under "LIST" ones. If you don't care about those finer points you could just use:

XDocument doc = XDocument.Load("foo.xml");
var items = doc.Descendants("ITEM");


An alternative syntax would be to chain the Descendents method to specifically get the ITEM nodes which are children of the LIST nodes:

XDocument doc = XDocument.Load("foo.xml");
var nodes = doc.Descendants("LIST").Descendants("ITEM");
0

精彩评论

暂无评论...
验证码 换一张
取 消