XSLT按属性值排序

11

我有一个关于如何根据属性值排序的问题。

我有以下源文档,并希望通过标题类值的值对轨道项目进行排序。

希望有人能帮忙解决这个问题。

input.xml:

<trackList>

    <track>
        <location>http://localhost/vmydoc</location>
        <title class="STD">Data Two</title>
    </track>
    <track>
        <location>http://localhost/vmydoc</location>
        <title class="SH">Data Three</title>

    </track>
    <track>
        <location>http://localhost/vmydoc</location>
        <title class="STD">Data Four</title>

    </track>
    <track>
        <location>http://localhost/vmydoc</location>
        <title class="SH">Data Five</title>

    </track>
</trackList>

最终输出应该如下所示:

output.xml:

<trackList>
        
    <track>
        <location>http://localhost/vmydoc</location>
        <title class="SH">Data Three</title>
            
    </track>
        
    <track>
        <location>http://localhost/vmydoc</location>
        <title class="SH">Data Five</title>
            
    </track>
        
    <track>
        <location>http://localhost/vmydoc</location>
        <title class="STD">Data Four</title>
            
    </track>
    <track>
        <location>http://localhost/vmydoc</location>
        <title class="STD">Data Two</title>
    </track>
</trackList>

我已经尝试了以下方法,但它并没有起作用。

my-stylesheet.xsl:

<xsl:for-each-group select="title" group-by="@class">
                        
    <xsl:for-each select="current-group()">
        <xsl:value-of select="@class"/>
    </xsl:for-each>
                        
</xsl:for-each-group>

谢谢。


你的样例输入中第一个locationtitle没有被<track>标记包围,这是一个复制/粘贴错误还是你的输入XML文件的特点? - JLRishe
这明显是复制粘贴错误。应该用 <track></track> 包裹它们。我已经纠正了。 - ManUO
1个回答

19
你可以按照以下方式进行操作:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="trackList">
    <xsl:copy>
      <xsl:apply-templates select="track">
        <xsl:sort select="title/@class"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

在使用您提供的样例输入时,结果为:

<trackList>
  <track>
    <location>http://localhost/vmydoc</location>
    <title class="SH">Data Three</title>

  </track>
  <track>
    <location>http://localhost/vmydoc</location>
    <title class="SH">Data Five</title>

  </track>
  <track>
    <location>http://localhost/vmydoc</location>
    <title class="STD">Data Two</title>
  </track>
  <track>
    <location>http://localhost/vmydoc</location>
    <title class="STD">Data Four</title>

  </track>
</trackList>

如果它们在一个单一的智能表单中,您无法拥有多个字段值,例如此处:http://stackoverflow.com/questions/33372683/how-to-sort-entries-of-xml-using-xslt?noredirect=1#comment54539949_33372683 - Si8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接