XSL - 将唯一且已排序的数据存储在变量中

时间:2018-06-07 09:28:10

标签: sorting xslt grouping unique

使用XSLT 2.0和Apache FOP我希望能够创建一个新变量,在category内部包含唯一且已排序的值,但保留节点。所以新变量应该有以下节点:

<category>1. First Aid</category>
<category>2. Access control</category>
<category>3. Fire safety</category>
<category>4. Recognition</category>

输入XML如下:

<equipment>
    <E0132>
        <category>1. First Aid</category>
        <description>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</description>
    </E0132>
    <E0133>
        <category>1. First Aid</category>
        <description>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</description>
    </E0133>
    <E4122>
        <category>3. Fire safety</category>
        <description>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</description>
    </E4122>
    <E4182>
        <category>3. Fire safety</category>
        <description>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</description>
    </E4182>
    <E4622>
        <category>2. Access control</category>
        <description>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</description>
    </E4622>
    <E5225>
        <category>4. Recognition</category>
        <description>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</description>
    </E5225>
</equipment>

关于XSL,这是我到目前为止所做的:

<xsl:variable name="equipment">
    <xsl:for-each-group select="//equipment/node()" group-by="category">
        <xsl:sort select="." order="ascending" />
        <xsl:value-of select="."/>              
    </xsl:for-each-group>        
</xsl:variable>

但它没有按预期工作。它不包含我想要的category节点,我不知道如何在这里集成distinct-values() XSL函数以实现单一性。

1 个答案:

答案 0 :(得分:1)

您可以使用current-grouping-key()函数存储值。以下是更新的变量声明。

<xsl:variable name="equipment">
    <xsl:for-each-group select="//equipment/*/category" group-by=".">
        <xsl:sort select="." order="ascending" />
        <category>
            <xsl:value-of select="current-grouping-key()"/>
        </category>              
    </xsl:for-each-group>   
</xsl:variable>

检查变量内容

<xsl:copy-of select="$equipment" />

将输出显示为

<category>1. First Aid</category>
<category>2. Access control</category>
<category>3. Fire safety</category>
<category>4. Recognition</category>

编辑:要在循环中打印变量值,请尝试以下

<!-- print variable values -->
<xsl:for-each select="$equipment/category" >
    <xsl:value-of select="." />
    <xsl:text>&#xA;</xsl:text>
</xsl:for-each>

输出

1. First Aid
2. Access control
3. Fire safety
4. Recognition