xml - 模仿 XSLT 1.0 中的位置(节点集)?

标签 xml xslt position xslt-2.0 xslt-1.0

XSLT 2.0 提供了将节点集参数作为 position() 函数的一部分进行传递的优势。不幸的是,这在 XSLT 1.0 中不可用。有没有办法模仿这种行为?

例如,给定这个 XML:

<wishlists>
  <wishlist name="Games">
    <product name="Crash Bandicoot"/>
    <product name="Super Mario Brothers"/>
    <product name="Sonic the Hedgehog"/>
  </wishlist>
  <wishlist name="Movies">
    <product name="Back to the Future"/>
  </wishlist>
</wishlists>

和这个 XSLT 2.0:

<xsl:value-of select="position(/wishlists/wishlist/product)"/>

在处理最后的“回到 future ”节点时,将返回值“4”。

不幸的是,我似乎能够使用 XSLT 1.0 获得的最接近结果如下:

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

但是,我会在同一个“回到 future ”节点中得到值“1”,而不是我真正想要的值“4”。

最佳答案

您可以使用 preceding axis .

这个 XSLT 1.0 样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

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

  <xsl:template match="product">
    <product position="{count(preceding::product) + 1}">
      <xsl:apply-templates select="@*"/>
    </product>    
  </xsl:template>

</xsl:stylesheet>

应用于您的 XML 输入会产生:

<wishlists>
   <wishlist name="Games">
      <product position="1" name="Crash Bandicoot"/>
      <product position="2" name="Super Mario Brothers"/>
      <product position="3" name="Sonic the Hedgehog"/>
   </wishlist>
   <wishlist name="Movies">
      <product position="4" name="Back to the Future"/>
   </wishlist>
</wishlists>

关于xml - 模仿 XSLT 1.0 中的位置(节点集)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9397608/

相关文章:

java - 选中时更改复选框颜色?

java - 对 (Button)findViewById 的错误感到困惑

html - 固定位置在 Chrome 中不起作用

python - 如何返回与输入数字相同的数字在python列表中的位置?

xslt - 在 XSLT 中使用 HTML 实体(例如 )

java - 获取 Canvas 中的鼠标位置(java)

iphone - 如何使用 GDataXML 解析器解析此 xml?

javascript - 如何从 xml 中提取特定内容(在页面加载时)?

xslt - 生成动态xmlns

html - 客户端 XSLT 的当前状态