简体   繁体   English

使用LINQ查询XML文件

[英]Using LINQ to query XML file

I have an XML document that looks like this. 我有一个看起来像这样的XML文档。 It has been created using the Diagram feature of DevExpress. 它是使用DevExpress的图表功能创建的。

<XtraSerializer version="17.1.3.0">
   <Items>
     <Item1 ItemKind="DiagramRoot">
       <Children>
         <Item1  Shape="Triangle" Content="AA" /> 
         <Item2  Shape="Triangle" Content="AB" /> 
         <Item3  Shape="Octagon"  Content="A"  /> 
       </Children>
     </Item1>
   </Items>
 </XtraSerializer>

I would like to Query it to return the Shape and Content of all items under Children . 我想查询它以返回Children下所有项目的ShapeContent I tried the query below but it does not work. 我尝试了下面的查询,但它不起作用。

XDocument document = XDocument.Load("C:\\Users\\Jb\\Desktop\\Network_Base.xml");

var items = from r in document.Descendants("Children")
            select new
            {
                Content = r.Attribute("Content").Value,
                Shape = r.Attribute("Shape").Value,
            };

foreach (var r in items)
{               
    Console.WriteLine(r.Content + r.Shape);
}

Try following : 尝试以下操作:

var results = doc.Descendants("Children").FirstOrDefault().Elements()
                 .Where(x => x.Attribute("Content") != null).Select(r => new {
                     Content = r.Attribute("Content").Value,
                     Shape = r.Attribute("Shape").Value
                 }).ToList();

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

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