I’ve an xml file (Sample.xml) which has the following structure
<RootElement>
<Children>
<Child Name="FirstChild" Start="0" End="2">
<Sibling Name="Test1" />
<Sibling Name="Test2" />
<AdditionalSibling Name="Add_Test_1" />
<AdditionalSibling Name="Add_Test_2" />
<MissingSibling Name="Miss_Test_1" />
<MissingSibling Name="Miss_Test_2" /
</Child>
<Child Name="SecondChild" Start="0" End="2">
<Sibling Name="Test3" />
<Sibling Name="Test4" />
</Child>
<Child Name="ThirdChild" Start="0" End="2">
<Sibling Name="Test5" />
<Sibling Name="Test6" />
</Child>
<Child Name="FourthChild" Start="0" End="2">
<Sibling Name="Test7" />
<Sibling Name="Test8" />
</Child>
<Child Name="FifthChild" Start="0" End="2">
<Sibling Name="Test9" />
<Sibling Name="Test10" />
</Child>
<Child Name="SixthChild" Start="0" End="2">
<Sibling Name="Test11" />
<Sibling Name="Test12" />
</Child>
<MatchedChilds>
<Child Name="FirstChild" />
<Child Name="SecondChild" />
<Child Name="ThirdChild" />
<Child Name="FourthChild" />
<Child Name="FifthChild" />
<Child Name="SixthChild" />
</MatchedChilds>
</Children>
</RootElement>
i need to read the attribute values of the element” Child” which is directly under “RootElement”
Now i’m using the LINQ query like
List<string> lst = (from element in XDocument.Load(Application.StartupPath + "\\Sample.xml")
.Descendants("Child")
group element by element.Attribute("Name").Value into KeyGroup select KeyGroup.Key )
.ToList();
but it returns the attribute value of “Name” of all the “Child” element in the file.
Please give me a better solution to do this using XML to LINQ
Thanks in advance
Use something like this:
Note the use of
Elements()instead ofDescendants(). That will get you all the name attributes. It’s unclear to me why you were grouping in your original sample code, but hopefully this will get you going.