根据 xml 标签的属性值显示输出

Displaying output based on attribute value of xml tag

<?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" 值来定位它们,我该怎么做?

I want to position them based on the attribute "num" value how do i do that??

这种操作称为排序。对 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