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

Jos*_*ola 4 .net xml sorting

因此,您有一个第三方Web服务,它喜欢滥用XML并按顺序返回内容,使您的编程完全痛苦.例如...

<file>
  <node1>Foo</node1>
  <price>4.99</price>
  <node2>
    <key>XX999</key>
  </node2>
</file>
Run Code Online (Sandbox Code Playgroud)

按价格排序大约有一千个.

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

我需要将结果作为已排序的XML文件.谢谢!

编辑: .NET 2.0版(没有LINQ)

Mit*_*eat 11

以下是使用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>
Run Code Online (Sandbox Code Playgroud)

这个变换(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>
Run Code Online (Sandbox Code Playgroud)

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

XslCompiledTransform xslt= new XslCompiledTransform();
xslt.Load(@"c:\stylesheet.xsl");

xslt.Transform(@"C:\file.xml", @"c:\sorted.xml");
Run Code Online (Sandbox Code Playgroud)

在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>
Run Code Online (Sandbox Code Playgroud)