使用 xsl:for-each 循环代替 xsl:variable 中的 select="expr" 进行查询时遇到的问题

Issue faced while using xsl:for-each loop to query instead of select="expr" in xsl:variable

当我对 select 元素使用 2 种不同的技术时,变量 $var 的计数不同:-

<xsl:variable name="var" select="$doc//ns:abc | $doc//ns:xyz"/>

<xsl:message select="count($var)"/>

给出适当的计数

但是

<xsl:variable name="var" >
    <xsl:for-each select="$doc//ns:abc | $doc//ns:xyz">
        <xsl:copy-of select="."/>
    </xsl:for-each>
</xsl:variable>

<xsl:message select="count($var)"/>

给出 1

如何使用 for-each 循环获得适当的计数。因为我想按排序顺序存储元素,这只能通过在 xsl:for-each/.

中使用 xsl:sort/ 来完成

<xsl:variable name="var" >
    <xsl:for-each select="$doc//ns:abc | $doc//ns:xyz">
        <xsl:copy-of select="."/>
    </xsl:for-each>
</xsl:variable>

变量的值是单个文档片段节点,其中包含您 select 元素的副本。

您需要在 xsl:variablexsl:sequence

上使用 as 属性
<xsl:variable name="var" as="node()*">
    <xsl:for-each select="$doc//ns:abc | $doc//ns:xyz">
        <xsl:sequence select="."/>
    </xsl:for-each>
</xsl:variable>

或者干脆

<xsl:variable name="var" as="node()*">
    <xsl:sequence select="$doc//ns:abc | $doc//ns:xyz"/>
</xsl:variable>

到 select 来自输入文档的节点作为节点序列。

请注意,XPath 3 也有一个 sort 函数,因此即使您需要对输入节点进行排序,您也不需要像 xsl:for-each/xsl:sortxsl:perform-sort/xsl:sort 这样的 XSLT 元素,但可以简单地在 select XPath 表达式中使用 sort 函数。