【问题标题】:concatenating two xPaths in XSLT在 XSLT 中连接两个 xPath
【发布时间】:2025-12-18 17:45:02
【问题描述】:

在我的 XSLT 脚本中,我正在调用递归模板,并且我想将 xPath 作为参数传递给每次迭代。在每次迭代中,我想将孩子的 xPath(*/) 连接到当前路径(请参阅代码)。所以我使用了 concat() 函数,因为它返回一个字符串,所以我无法使用该路径来打印该路径的内容。

<xsl:copy-of select="$path" /> <!--This requests a xPath, not a string-->

谁能告诉我如何连接两个 xpath 或如何将字符串转换为 xpath。

谢谢。

    <xsl:template match="/">
        <xsl:call-template name="repeatable" >
            <xsl:with-param name="limit" select="10" />
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="repeatable">
        <xsl:param name="index" select="1" />
        <xsl:param name="limit" select="1" />
        <xsl:param name="path" select="@*" />

        <xsl:copy-of select="$path" />

        <xsl:if test="($limit >= $index)">
            <xsl:call-template name="repeatable">
                <xsl:with-param name="index" select="$index + 1" />
                <xsl:with-param name="path" select="concat('*/', $path)" />
            </xsl:call-template>
        </xsl:if>
    </xsl:template>

【问题讨论】:

  • 你能告诉我们这段代码的目的/期望的结果是什么吗?也许有更好的方法来完成你想做的事情。请给我们一个示例输入和输出。

标签: xslt xpath concat


【解决方案1】:

当我在等待您回答我上面的问题时,这里有一个 XSLT,可以完成您似乎尝试做的事情:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="@*">
    <xsl:value-of select="concat(name(), ' = ', ., '&#xA;')"/>
  </xsl:template>

  <xsl:template match="/">
    <xsl:call-template name="repeatable" >
      <xsl:with-param name="limit" select="10" />
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="repeatable">
    <xsl:param name="index" select="1" />
    <xsl:param name="limit" select="1" />
    <xsl:param name="current" select="." />

    <xsl:apply-templates select="$current/@*" />

    <xsl:if test="($limit >= $index)">
      <xsl:call-template name="repeatable">
        <xsl:with-param name="index" select="$index + 1" />
        <xsl:with-param name="limit" select="$limit" />
        <xsl:with-param name="current" select="$current/*" />
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>

在以下输入上运行时:

<root a1="a" a2="b">
  <cont a3="c" a4="d">
    <child a5="e" a6="f" />
  </cont>
  <cont a7="g" a8="h">
    <child a9="i" a10="j">
      <subchild a11="k" a12="l" />
    </child>
  </cont>
</root>

结果是:

a1 = a
a2 = b
a3 = c
a4 = d
a7 = g
a8 = h
a5 = e
a6 = f
a9 = i
a10 = j
a11 = k
a12 = l

这是否接近您想要做的事情?如果不是,请澄清。

【讨论】:

  • 非常感谢。这正是我想要的。
【解决方案2】:

您要做的是动态创建 xpath 并使用它。这在 XSLT3.0 中是可能的,要使用的函数是 evaluate()。

【讨论】: