简体   繁体   中英

Using LINQ to query XML file

I have an XML document that looks like this. It has been created using the Diagram feature of 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 . 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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