xsl if条件显示相同级别的元素

时间:2012-02-02 21:27:03

标签: xml xslt if-statement

如果conditon

,我如何显示相同级别的元素值

例如

XML

<catalog>
<cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
</cd>
<cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
</cd>
<cd>
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <country>USA</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
</cd>

XSLT

<xsl:if test="/catalog/cd/country='UK'">
    <xsl:value-of select="title"/>
    <xsl:value-of select="artist"/>
</xsl:if>

这不会影响英国级元素的标题和艺术家

我知道解决问题的一种方法是使用每个循环,但我正在寻找一种有效的方法

2 个答案:

答案 0 :(得分:3)

此:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:template match="/catalog/cd">
    <xsl:if test="country = 'UK'">
        <xsl:value-of select="title"/>
        <xsl:value-of select="artist"/>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

产地:

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

Hide your heartBonnie Tyler

答案 1 :(得分:3)

这可以仅使用模板完成:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/catalog/cd[country='UK']" priority="1">
        <xsl:value-of select="title"/>
        <xsl:value-of select="artist"/>
    </xsl:template>
    <xsl:template match="/catalog/cd">
        <!--  handle non-UK CDs here -->
    </xsl:template>
</xsl:stylesheet>

还有许多其他方法 - 当然,根据您的要求 - 安排模板以生成所需的输出。例如,您最终可能会使用显式模板来处理titleartist元素(或明确隐藏每个cd的所有其他子元素)。

所有这些都取决于您的特定需求,但我想在此处展示的一般观点是,当您在模板匹配中正确捕获目标元素时,您将获得更多功能(并最终获得更清晰的代码) (而不是 ad-hoc 条件)。

相关问题