首页 文章

XSLT动态xpath子选择

提问于
浏览
0

我需要通过给定路径递归选择子项 . 这是我的XML结构:

<items>
   <item name="first">
      <item name="fist-first">
         [...]
      </item>
      <item name="first-second">
         [...]
      </item>
      [...]
   </item>
</items>

我需要通过xsl:param传递的路径选择一个特定的项目(比如“0-1”来选择第一个元素的第二个子元素) . 我有一个字符串表示与其子位置有关的实际节点路径 .

有人知道这是否可能并给我一些帮助?

我用saxon 9.8he .

提前致谢

2 回答

  • 0

    首先使用 tokenize() 函数将 $path 转换为正整数序列,例如(1,4,6),然后调用此递归函数:

    <xsl:function name="f:by-path" as="element()?">
     <xsl:param name="origin" as="element()*"/>
     <xsl:param name="path" as="xs:integer*"/>
     <xsl:sequence select="
         if (empty($path)) 
         then $origin 
         else $origin[head($path)]/f:by-path(*, tail($path))"/>
    </xsl:function>
    
  • 0

    使用Saxon 9.8和XSLT 3.0,您可以使用带有路径表达式的static parameter

    <xsl:param name="path" static="yes" as="xs:string" select="'/items/item[1]/item[2]'"/>
    

    如果您想使用该路径,则不会使用普通的 select 属性,而是使用相应的shadow attribute _select="{$path}" ,例如

    <xsl:template match="/">
      <xsl:copy-of _select="{$path}"/>
    </xsl:template>
    

    然后,您可以像运行任何其他参数一样运行样式表时设置该参数 .

相关问题