0

Is there a way we can sort xmlnodes based on attribute values, consider I can't use linq. Since I'm using .NET 2.0.

Example:

<Root a="1">
   <I aa="1" b="2">
   <I aa="5" b="2">
   <I aa="3" b="2">
   <I aa="4" b="2">
</Root>

Should be like ->

<Root a="1">
    <I aa="1" b="2">
    <I aa="3" b="2">
    <I aa="4" b="2">
    <I aa="5" b="2">
</Root>

Please help.

theduck
  • 2,589
  • 13
  • 17
  • 23
user2711884
  • 1
  • 1
  • 1
  • 7
  • I think this is a duplication to this [post](http://stackoverflow.com/questions/4604100/how-to-sort-xml-document-in-linq-by-an-attribute-value?rq=1) – Dong Aug 27 '13 at 12:03
  • "He who tries to grab too much will end up with nothing". (it's connected to my deleted post) – xanatos Aug 27 '13 at 13:28

1 Answers1

12

To sort use following:

var xml= xDoc.Element("Root")
                .Elements("I")
                .OrderByDescending(s => (int) s.Attribute("aa"));

Then to save it:

XDocument doc = new XDocument(new XElement("Root", xml));
doc.Save("C:\\Something.xml");

UPDATE

You can use XSLT for this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/*">
        <xsl:copy>
            <xsl:for-each select="I">
                            <xsl:sort select="@aa" order="ascending"/>
                    <xsl:copy-of select="."/>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

And invoke it (quoting How to apply an XSLT Stylesheet in C# ):

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.xml",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
Community
  • 1
  • 1
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116