问题描述
我一直在尝试学习如何在 xslt 中编写代码,目前我一直在学习如何围绕 xsl:apply-templates 标签使用条件测试.
I've been trying to learn how to code in xslt and currently am stuck on how to use conditional tests around the xsl:apply-templates tag.
这是我正在测试的 xml.
Here's the xml that I am testing.
<?xml version="1.0" encoding="utf-8"?>
<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:template match="/">
<xsl:apply-templates select="catalog/cd" />
</xsl:template>
<xsl:template match="cd">
<p>
<xsl:apply-templates select="artist" />
<br />
<xsl:apply-templates select="country" />
<br />
<xsl:if test="country != 'USA' and year != '1985'">
<xsl:apply-templates select="year" />
</xsl:if>
</p>
</xsl:template>
<xsl:template match="artist">
<xsl:value-of select="." />
</xsl:template>
<xsl:template match="country">
<xsl:value-of select="." />
</xsl:template>
<xsl:template match="year">
<xsl:value-of select="." />
</xsl:template>
这是我的输出:
Bob Dylan
USA
Bonnie Tyler
UK
1988
Dolly Parton
USA
这是我期望的输出:
Bob Dylan
USA
Bonnie Tyler
UK
1988
Dolly Parton
USA
1982
即使我只想在国家/地区的值为 USA 且年份的值为 1985 时删除年份,但每次国家/地区的值为 USA 时都会删除年份.有没有更好的方法可以使用应用模板?
Even though I want to remove the year only when country has a value of USA and year has a value of 1985 it is removing the year every time country has a value of USA only. Is there a better way I can use apply-templates?
推荐答案
您可能更喜欢将模板直接应用于所需的节点集,而无需有条件的if"检查.
You might prefer to apply templates to the wanted node set directly, without conditional "if" check.
<xsl:apply-templates select="year[not(../country='USA' and ../year='1985)]" />
这篇关于围绕 xsl:apply-templates 的条件测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!