繁体   English   中英

XSLT中具有相同名称的多个子节点

[英]Multiple child nodes of the same name in XSLT

我有以下XML:

<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Artist 1</artist>
        <country>USA</country>
        <artist>Artist 2</artist>
        <artist>Artist 3</artist>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
    </cd>
</catalog>

现在,在XSLT中,我想遍历<cd>的子节点,并检查它是<title>还是<artist><country>等...到目前为止,我已经完成了以下XSLT:

<xsl:for-each select="catalog/cd">
        <table>
            <tr>
                <th colspan="2"><xsl:value-of select="title"/></th>
            </tr>
            <xsl:choose>
                <xsl:when test="artist">
                    <xsl:apply-templates select="artist"/>
                </xsl:when>
                <xsl:when test="country">
                    <xsl:apply-templates select="country"/>
                </xsl:when>
                <xsl:when test="company">
                    <xsl:apply-templates select="company"/>
                </xsl:when>
                <xsl:when test="price">
                    <xsl:apply-templates select="price"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:apply-templates select="year"/>
                </xsl:otherwise>
            </xsl:choose>
</xsl:for-each>

但是由于某种原因, <artist>在显示第一个,而其他未显示。 我想要的是即使有<artist><country>和另一个<artist> ,也要按顺序显示每个节点。 有人有什么想法吗?

您可以通过完全删除choose来完成此操作。 xsl:choose一旦when测试中第一次成功就停止,实际上,您是在说“如果有一位artist那么就展示出来,否则,如果有一个country那么就展示出来,否则……”。

<xsl:for-each select="catalog/cd">
    <table>
        <tr>
            <th colspan="2"><xsl:value-of select="title"/></th>
        </tr>
        <xsl:apply-templates select="artist"/>
        <xsl:apply-templates select="country"/>
        <xsl:apply-templates select="company"/>
        <xsl:apply-templates select="price"/>
        <xsl:apply-templates select="year"/>
    </table>
</xsl:for-each>

在应用模板之前,无需检查元素是否存在; apply-templates将处理其select表达式找到的所有节点,如果select找到任何内容,则apply-templates将不执行任何操作。

如果要按文档顺序处理元素,而不是首先按艺术家,然后按国家/地区处理,则只需将它们分组为一个apply-templates

<xsl:apply-templates select="artist | country | company | price | year" />

或者,如果您不想显式命名所有元素,则将title逻辑移到其自己的模板中

<xsl:template match="title">
  <tr>
    <th colspan="2"><xsl:value-of select="."/></th>
  </tr>
</xsl:template>

然后您的主模板可以简单地是

<xsl:for-each select="catalog/cd">
    <table>
        <xsl:apply-templates select="*" />
    </table>
</xsl:for-each>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM