在XSLT中对兄弟元素进行排序

时间:2017-09-08 18:10:44

标签: xml sorting xslt xslt-1.0

假设以下XML输入 -

<parent>
    <name>Bob</name>
    <name>Alice</name>
    <another-attribute>something</another-attribute>
    <city>Kansas City</city>
    <city>Atlanta</city>
</parent>

如何按字母顺序对同类属性进行排序?换句话说,这是预期的输出 -

<parent>
    <name>Alice</name>
    <name>Bob</name>
    <another-attribute>something</another-attribute>
    <city>Atlanta</city>
    <city>Kansas City</city>
</parent>

我能够通过stackoverflow中的各种示例完成一些更复杂的排序,但我正在努力解决这个问题。

免责声明:我是一名XSLT菜鸟,所以请轻易放弃滥用。

1 个答案:

答案 0 :(得分:0)

一种方法是将for-each es与xsl:sort一起使用 在下面的代码中,for-each选择所有name个节点,并按其text()内容对其进行排序。分别对city个元素相同。中间的xsl:copy-of复制了不是namecity元素本身的所有其他元素。

开头的xsl:copy复制当前所选元素parent,以下xsl:copy-of复制其(可能)属性。

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">    
    <xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="no"/>

    <xsl:template match="parent">
      <xsl:copy>
        <xsl:copy-of select="@*" />
        <xsl:for-each select="name">
          <xsl:sort select="text()" />
          <xsl:copy-of select="." />
        </xsl:for-each>
        <xsl:copy-of select="*[not(self::name | self::city)]" />
        <xsl:for-each select="city">
          <xsl:sort select="text()" />
          <xsl:copy-of select="." />
        </xsl:for-each>
      </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
相关问题