2015-03-03 114 views
1
<?xml version="1.0" encoding="UTF-8"?> 

<provinces> 
<name num="5">Alberta</name> 
<name num="3">British</name> 
<name num="1">Manitoba</name> 
<name num="4">New Brunswick</name> 
<name num="2">Newfoundland</name> 
</provinces> 

我想输出显示输出

1. Manitoba 
2. Newfoundland 
3. British 
4. New Brunswick 
5. Alberta 

我使用下面的XSLT

<?xml version="1.0" encoding="US-ASCII"?> 
<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text" /> 

    <xsl:template match="provinces"> 
    <xsl:apply-templates select="name" /> 
    </xsl:template> 

    <xsl:template match="name"> 
    <xsl:value-of select="position()" /> 
    <xsl:text>. </xsl:text> 
    <xsl:value-of select="." /> 
    </xsl:template> 

</xsl:stylesheet> 

我知道这样不给我想要的这种方式输出,但这是我得到的。

我想根据属性“num”的值来定位它们,我该怎么做?

回答

1

我想根据属性“num”的值来定位它们,我该怎么做?

这种操作叫做排序。排序里面xsl:apply-templates输入元素就是你需要:

<xsl:apply-templates select="name"> 
    <xsl:sort select="@num"/> 
</xsl:apply-templates> 

此外,为了避免让在一行中的所有文本,输出一个换行符如果当前name节点不是最后一个。

XSLT样式表

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

    <xsl:template match="provinces"> 
    <xsl:apply-templates select="name"> 
     <xsl:sort select="@num" data-type="number"/> 
    </xsl:apply-templates> 
    </xsl:template> 

    <xsl:template match="name"> 
    <xsl:value-of select="concat(position(),'. ')" /> 
    <xsl:value-of select="." /> 
    <xsl:if test="position() != last()"> 
     <xsl:text>&#10;</xsl:text> 
    </xsl:if> 
    </xsl:template> 

</xsl:stylesheet> 

文本输出

1. Manitoba 
2. Newfoundland 
3. British 
4. New Brunswick 
5. Alberta 
+2

的'的'最好是'的',以确保排序完成数字。否则,更多的项目'10'会在'2'之前结束。 – 2015-03-03 12:58:17

+0

@MartinHonnen感谢马丁,你是对的。我编辑了我的答案。 – 2015-03-03 13:03:15