xslt copy of all nodes to variable

2020-04-21 01:10发布

How one can assign to variable a copy of another variable that contains a set of nodes? Here is my code:

    <xsl:variable name="btchs" select="$idoc/E1EDL20/E1EDL24[./HIPOS != 0]"></xsl:variable>
    <xsl:variable name="lines" select="$idoc/E1EDL20/E1EDL24[./HIPOS = 0]"></xsl:variable>
    <xsl:variable name="cnt" select="count($btchs)"></xsl:variable>
    <xsl:variable name="blines">
        <xsl:choose>
            <xsl:when test="$cnt=0">
                Here I want to make a copy all nodes of $lines variable
            </xsl:when>
            <xsl:otherwise>
                Here I want to make a copy all nodes of $btchs variable             
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>

I define another variable because later it's used as for-each loop counter.

    <xsl:for-each select="$blines">
    ...
    </xsl:for-each> 

标签: xml xslt
2条回答
forever°为你锁心
2楼-- · 2020-04-21 01:33

That depends on if you use XSLT-1.0 or XSLT-2.0.

In XSLT-1.0 the following quote is determinative:

In XSLT 1.0 the result tree fragment (RTF) type is like a node-set, but it is really a second-class citizen. An RTF is what you get whenever you use xsl:variable to construct a temporary tree. The problem is that you can't then use an XPath expression to access the innards of this tree, unless you use a vendor-specific extension function, usually called something like node-set(), to convert the RTF into a first-class node-set (consisting of one root node).

So in XSLT-1.0 you only get an RTF which cannot be queried with further XPath queries and is therefore unable to fulfill your desire.

Returning to the core of your question, the following rules do apply according to your XSL version:

  • 1.0: <xsl:variable name="abc" select="..." /> --> queryable
  • 1.0: <xsl:variable name="bcd"><xsl:whatever-function>...</xsl:whatever-function> --> NOT queryable
  • 2.0: <xsl:variable name="abc" select="..." /> --> queryable
  • 2.0: <xsl:variable name="bcd"><xsl:whatever-function>...</xsl:whatever-function> --> queryable - does return all nodes in that variable as a tree.

Synopsis: You cannot make a complexly constructed XSLT-1.0 variable contain a fully queryable subset of your tree!

查看更多
beautiful°
3楼-- · 2020-04-21 01:46

Looking at your XSLT fragment, it looks like you want the blines variable to contain all the E1EDL24 elements where HIPOS is not zero, and if no-such elements exist, it should contain all E1EDL24 where HIPOS is zero.

If this is the case, instead of trying to copy the elements in the variables, you could define the blines variable as follows:

<xsl:variable name="blines" select="$btchs|$lines[not($btchs)]" />

This would reference the original elements in the source XML, rather than create a Result Tree Fragment, and so would still be queryable.

查看更多
登录 后发表回答