XSLT 1.0 - Create a Unique, Ordered List

℡╲_俬逩灬. 提交于 2020-01-30 09:46:47

问题


I'm trying to create a transform where I generate an ordered unique list (where a hyphen separates two values.

I have source

<?xml version="1.0"?>
<results>
    <result>
        <Name>Blue</Name>
        <Author>Hat</Author>
        <TrackNum>5</TrackNum>
    </result>
    <result>
        <Name>Red</Name>
        <Author>Car</Author>
        <TrackNum>2</TrackNum>
    </result>
    <result>
        <Name>Blue</Name>
        <Author>Hat</Author>
        <TrackNum>345</TrackNum>
    </result>
</results>

And want the output (ordered by 'Name')

:: Blue - Hat
:: Red - Car

XLST - This currently returns nothing (I know it's missing the second, hyphenated/concatenated value too)

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

<xsl:key name="Name" match="/results/result/Name/text()" use="." />

<xsl:template match="/">

  <xsl:for-each select="/results/results/Name/text()[generate-id()
                                       = generate-id(key('Name',.)[1])]">
    <li>
      <xsl:value-of select="."/>
    </li>
  </xsl:for-each>

</xsl:template>

</xsl:stylesheet>

回答1:


You were on the right track. You had a type-o in the XPath for your xsl:for-each select: /results/results should be /results/result. I made a slight adjustment to the key for what it matched against and used.

The following produces a unique list of Name and Author combinations, sorted by Name and then Author.

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

    <xsl:key name="Name-Author" match="results/result" use="concat(Name, ' - ', Author)" />

    <xsl:template match="/">

        <xsl:for-each select="/results/result[generate-id()
            = generate-id(key('Name-Author',concat(Name, ' - ', Author))[1])]">
            <xsl:sort select="Name"/>
            <xsl:sort select="Author"/>
            <li>
                <xsl:value-of select="concat(Name, ' - ', Author)"/>
            </li>
        </xsl:for-each>

    </xsl:template>

</xsl:stylesheet>


来源:https://stackoverflow.com/questions/16328097/xslt-1-0-create-a-unique-ordered-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!