按属性排序XML文件 [英] Sorting XML file by attribute

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

问题描述

我有以下的XML code:

I have a following XML code:

<Group>
    <GElement code="x">
        <Group>
            <GElement code="x">
                <fname>a</fname>
                <lname>b</lname>
            </GElement>
            <GElement code ="f">
                <fname>fa</fname>
            </GElement>
        </Group>
    </GElement>
    <GElement code ="f">
    </GElement>
</Group>

我想有输出排序code这样的:

I would like to have the output sorted by "code" like:

<Group>
    <GElement code ="f">
    </GElement>
    <GElement code="x">
        <Group>
            <GElement code ="f">
                <fname>fa</fname>
            </GElement>
            <GElement code="x">
                <fname>a</fname>
                <lname>b</lname>
            </GElement>
        </Group>
    </GElement>
</Group>

树的深度可以生生不息即GElement可以有另一个集团等。

The depth of the tree can be endless i.e. the GElement can have another Group and so on.

任何想法?

推荐答案

使用 XslCompiledTransform 请参阅MSDN )这个styleshet适用于您的XML文档:

Use XslCompiledTransform (see MSDN) to apply this styleshet to your XML document:

<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <!-- the identity template copies everything verbatim -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>

  <!-- special template for <Group> that sorts its children -->
  <xsl:template match="Group">
    <xsl:copy>
      <xsl:copy-of select="@*" /> <!-- copy attributes, if any -->
      <xsl:apply-templates select="GElement">
        <xsl:sort select="@code" />
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

XML树的嵌套深度可以是任意的。

XML tree nesting depth can be arbitrary.

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

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