0

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);
}

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

6 Comments

Hi. Thank you for your help. Unfortunately it didn't work. I get an error when the query is executed.
I tested it as well. It works. Is your xml different than what you posted?
I tested it with the posted code before posting and did not get any errors. Add picture of results
Actually you are right, it works, i made stupid mistake, thanks a lot.
Hi again. If my xml file has another item like this: <Item4 Shape="Arrow" Start="AA" End="A" /> . The query you gave does not work since item4 does not have the same Attribute as the others. How can I exclude item4 from the query?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.