VSe
VSe

Reputation: 929

Extract node value by calculating absolute position

My source XML looks:

  <test>
         <text1>Test</text1>
         <text2>Test</text2>
         <text2>Test</text2>
     <section>
         <text1>Test<bold>content</bold></text1>
         <text1>Test</text1>
         <text2>Test</text2>
         <text2>Test</text2>
     </section>
  </test>

Want to extract the value of 6th node, based on the absolute number of the element (overall count). The absolute number of the element has been identified using <xsl:number level="any" from="/" count="*"/>.

Upvotes: 0

Views: 404

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122394

The XPath expression /descendant::*[6] should give you the element you need.

<xsl:template match="/">
  <xsl:copy-of select="/descendant::*[6]" />
</xsl:template>

outputs

<text1>Test<bold>content</bold></text1>

Note that this is an example of the difference between descendant:: and // - //*[6] would give you all elements that are the sixth child element of their respective parent, rather than simply the sixth element in the document in depth-first order.

Upvotes: 2

Jirka Š.
Jirka Š.

Reputation: 3428

This xslt

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
        <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

        <xsl:variable name="allElements" select="//element()" />

        <xsl:template match="/">
            <output>
                <xsl:value-of select="$allElements[6]" />
            </output>
        </xsl:template>

    </xsl:stylesheet>

will result in

<?xml version="1.0" encoding="UTF-8"?>
<output>Testcontent</output>

Upvotes: 0

Related Questions