C#:使用属性值排序的XML节点 [英] C#: Sort xml node using attribute value

查看:589
本文介绍了C#:使用属性值排序的XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法,我们可以根据属性值,排序将XMLNode考虑,我不能使用LINQ 。由于我使用.NET 2.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.

例如:

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

应该是这样 - >

    <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.

推荐答案

要排序使用下列内容:

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");



更新

您可以使用XSLT此:

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>

和调用它(引用的如何在C#中使用XSLT样式表):

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.xml",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;

这篇关于C#:使用属性值排序的XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆