繁体   English   中英

按属性排序XML文件

[英]Sorting XML file by attribute

我有以下XML代码:

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

我希望输出按“代码”排序,如:

<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可以有另一个Group等等。

有任何想法吗?

使用XslCompiledTransform请参阅MSDN )将此styleshet应用于XML文档:

<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树的嵌套深度可以是任意的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM