profires
profires

Reputation: 13

Xpath query over xslt <collection> variable

I'm finding a way to use the xpath preceding/preceding-sibling functions to count the number of tag over the iteration on multiple xml file.

I'm using the 'collection' function to "merge" multiple xml, as below:

          <?xml version='1.0'?>
        <xsl:stylesheet version='2.0' xmlns:fo="http://www.w3.org/1999/XSL/Format"    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <xsl:output indent="yes"/>
            <xsl:variable name="input" select="collection('./docs.xml')"/>

            <xsl:template name="genTOC">
            ...

                <xsl:for-each select="$input/library">
                    <xsl:value-of select="count (preceding::library) +1" />
            ...

Where docs.xml contains reference to a series of xml file structured like below:

<library>
    <book>
        <title>The Art of Computer Programming</title>
        <price>198</price>
        <author>Donald Knuth</author>
        <ISBN>0201485419</ISBN>
    </book>
    <book>
        <title>The C Programming Language</title>
        <price>46.96</price>
        <author>Brian Wilson Kernighan</author>
        <ISBN>0131103628</ISBN>
    </book>
</library>

But seems that I'm not able to count the preceding as they are in another xml file. I've tried also with

count (../preceding::library)

Upvotes: 1

Views: 904

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

I think you simply want

            <xsl:for-each select="$input/library">
                <xsl:value-of select="position()" />

If you really think you need to navigate the collection then you can create a temporary tree (fragment) within a variable

<xsl:variable name="my-library">
  <xsl:copy-of select="$input/library"/>
</xsl:variable>

<xsl:for-each select="$my-library/library">
  <xsl:value-of select="1 + preceding-sibling::library"/>
</xsl:for-each>

but of course you consume much more memory doing that compared to simply processing the input collection.

Upvotes: 1

Related Questions