0

How can I extract sub nodes to a single list for processing in a template?

Consider the following XML.

<document>
  <menu></menu>
  <feature>
    <header>Header 1</header>
    <article>article 1</article>
    <article>article 2</article>
  </feature>
  <feature>
    <header>Heading 2</header>
    <article>article 1a</article>
    <article>article 2a</article>
  </feature>  
</document> 

I'd like to extract all the article nodes to a single list for processing in a template.

I need article nodes to be available at once, because I need to do calculations based on the number of articles there are.

1 Answer 1

1

you can try the following stylesheet:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ext="http://exslt.org/common"
    exclude-result-prefixes="ext">

    <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/">
        <xsl:variable name="list">
            <articles>
                <xsl:copy-of select="descendant::article"/>
            </articles>
        </xsl:variable>

        <xsl:variable name="vPass1" select="ext:node-set($list)"/>

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

    </xsl:template>

    <xsl:template match="articles">
        <xsl:copy>
            <xsl:text>Number of articles: </xsl:text><xsl:value-of select="count(article)"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

when applied your input, it produces:

<articles>Number of articles: 4</articles>
Sign up to request clarification or add additional context in comments.

1 Comment

Accepting this answer, but what I ended up doing was a select on the document element, and a for-each on feature/article. No reliance on extensions, low tech, but I understand that for-each can be frowned upon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.