LINQ Order By Query for XML



Hi I have the following problem:


I am trying to do the following on an XML file: sort all STRUCTs according to the ID attribute of STRING. But return a list of CONTENT objects. The XML can contain more than one element.



<OBJECT>
<CONTENT>
<STRUCT>
<STRING ID="2">string</STRING>
</STRUCT>
<STRUCT>
<STRING ID="1">string1</STRING>
</STRUCT>
</CONTENT>
</OBJECT>
<OBJECT>
<CONTENT>
<STRUCT>
<STRING ID="345">string</STRING>
</STRUCT>
<STRUCT>
<STRING ID="333">string</STRING>
</STRUCT>
</CONTENT>
</OBJECT>


I am using the following LINQ query, but the strings are not being sorted:



Dim Contents = From nm In origXML.Descendants("CONTENT")
Let ID = nm.Element("STRUCT").Element("STRING").Attribute("ID")
Order By ID Ascending
Select nm

For Each xmlString In Contents....


Desired output



<OBJECT>
<CONTENT>
<STRUCT>
<STRING ID="1">string</STRING>
</STRUCT>
<STRUCT>
<STRING ID="2">string1</STRING>
</STRUCT>
</CONTENT>
</OBJECT>
<OBJECT>
<CONTENT>
<STRUCT>
<STRING ID="333">string</STRING>
</STRUCT>
<STRUCT>
<STRING ID="345">string</STRING>
</STRUCT>
</CONTENT>
</OBJECT>


I know there must be other ways to do this, but I want to know if it's possible using LINQ?


Thanks


Rob


No comments:

Post a Comment