XSLT:如何在单个列表中选择多个子节点

时间:2014-03-27 06:31:13

标签: xslt-1.0

如何将子节点提取到单个列表以便在模板中处理?

考虑以下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> 

我想将所有article个节点提取到一个列表中,以便在模板中进行处理。

我需要一次提供article个节点,因为我需要根据文章的数量进行计算。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下样式表:

<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>

应用您的输入时,会产生:

<articles>Number of articles: 4</articles>