繁体   English   中英

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

[英]Mimicking position(node-set) in 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)"/>

当处理最后的“ Back to the Future”节点时,将返回值“ 4”。

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

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

但是,在同一个“ Back to the Future”节点中,我将获得一个“ 1”值,而不是我真正想要的“ 4”值。

您可以使用前一个轴

此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>

XSLT 2.0提供了将节点集参数作为position()函数的一部分传递的好处。

这个说法是错误的。 position()函数没有参数-在XPath 1.0或XSLT 2.0使用的XPath 2.0中。

您想要的是

count(preceding::product) +1

或者,可以使用xsl:number指令。

这是这两种方法的演示

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:variable name="vLastProd" select=
  "//product[@name='Back to the Future']"/>

 <xsl:template match="/">
     <xsl:value-of select="count($vLastProd/preceding::product) +1"/>
=========
<xsl:text/>
   <xsl:apply-templates select="$vLastProd"/>
 </xsl:template>

 <xsl:template match="product">
   <xsl:number level="any" count="product"/>    
 </xsl:template>
</xsl:stylesheet>

在提供的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>

使用这两种方法都可以获得所需的正确结果-和输出

4
=========
4

注意 :如果不直接输出xsl:number的结果,则需要将其捕获到变量的主体内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM