C#: Sort xml node using attribute value

后端 未结 1 1608
萌比男神i
萌比男神i 2020-12-18 17:20

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:



        
相关标签:
1条回答
  • 2020-12-18 18:04

    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) ;
    
    0 讨论(0)
提交回复
热议问题