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.

2
  • I think this is a duplication to this post Commented Aug 27, 2013 at 12:03
  • "He who tries to grab too much will end up with nothing". (it's connected to my deleted post) Commented Aug 27, 2013 at 13:28

1 Answer 1

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

2 Comments

Garath: I have mentioned in post that I can`t use linq. Please reply with some other answers. Thanks
Is XSLT allowed? It is in .NET 2.0

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.