代码之家  ›  专栏  ›  技术社区  ›  Josh Stodola

如何使用.NET对XML文件进行排序?

  •  4
  • Josh Stodola  · 技术社区  · 16 年前

    因此,您有一个第三方Web服务,它喜欢滥用XML并按顺序返回内容,这会使您的编程完全陷入困境。例如。。。

    <file>
      <node1>Foo</node1>
      <price>4.99</price>
      <node2>
        <key>XX999</key>
      </node2>
    </file>
    

    其中大约有一千种是按价格排序的。

    如何按键值重新排序此XML文档?

    我需要一个经过排序的XML文件。谢谢!

    编辑: .NET 2.0版(无LINQ)

    4 回复  |  直到 16 年前
        1
  •  11
  •   Cerebrus    16 年前

    下面介绍如何使用XSLT:

    假设您的数据采用此格式(file.xml):

    <?xml version="1.0"?>
    <listing>
    <file>
      <node1>Foo</node1>
      <price>4.99</price>
      <node2>
        <key>XX999</key>
      </node2>
    </file>
    <file>
      <node1>Bar</node1>
      <price>5.67</price>
      <node2>
        <key>aa743</key>
      </node2>
    </file>
    <file>
      <node1>Was</node1>
      <price>5.67</price>
      <node2>
        <key>rr321</key>
      </node2>
    </file>
    </listing>
    

    此转换(stylesheet.xsl):

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:strip-space elements="*"/>
      <xsl:output method="xml" indent="yes"/>
    
      <xsl:template match="listing">
        <xsl:copy>
          <xsl:apply-templates select="file">
            <xsl:sort select="node2/key" data-type="text"/>
          </xsl:apply-templates>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
    
    </xsl:stylesheet>
    

    与此.NET代码一起使用时(需要添加 using System.Xml;):

    XslCompiledTransform xslt= new XslCompiledTransform();
    xslt.Load(@"c:\stylesheet.xsl");
    
    xslt.Transform(@"C:\file.xml", @"c:\sorted.xml");
    

    在sorted.xml中生成此输出:

    <?xml version="1.0" encoding="utf-8"?>
    <listing>
      <file>
        <node1>Bar</node1>
        <price>5.67</price>
        <node2>
          <key>aa743</key>
        </node2>
      </file>
      <file>
        <node1>Was</node1>
        <price>5.67</price>
        <node2>
          <key>rr321</key>
        </node2>
      </file>
      <file>
        <node1>Foo</node1>
        <price>4.99</price>
        <node2>
          <key>XX999</key>
        </node2>
      </file>
    </listing>
    
        2
  •  3
  •   qux    16 年前

    应用XML样式表将源XML转换为适合您使用的XML格式。在XSL转换期间,可以轻松地按值对元素排序。

        3
  •  1
  •   Mark Cidade    16 年前

    当然,XSLT规则,但我会使用linq to xml(即 System.Xml.Linq 命名空间)。具体来说,您需要做的是这样的事情:

    newElement = new XElement(oldElement.Elements().OrderBy(x => x.Whatever);
    
        4
  •  0
  •   Ian Suttle    16 年前

    Linq to XML会为您处理这个问题吗?