围绕 xsl:apply-templates 的条件测试

Mdd*_*Mdd 5 xslt xslt-1.0

我一直在尝试学习如何在 xslt 中进行编码,目前仍停留在如何使用 xsl:apply-templates 标记周围的条件测试上。

这是我正在测试的 xml。

<?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>
Run Code Online (Sandbox Code Playgroud)

这是我的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>
Run Code Online (Sandbox Code Playgroud)

这是我的输出:

Bob Dylan
USA

Bonnie Tyler
UK
1988

Dolly Parton
USA
Run Code Online (Sandbox Code Playgroud)

这是我期望的输出:

Bob Dylan
USA

Bonnie Tyler
UK
1988

Dolly Parton
USA
1982
Run Code Online (Sandbox Code Playgroud)

即使我只想在国家/地区值为 USA 并且年份值为 1985 时删除年份,但每次国家/地区值为 USA 时都会删除年份。有没有更好的方法可以使用 apply-templates?

Emi*_*ggi 5

您可能更愿意将模板直接应用于所需的节点集,而不进行条件“if”检查。

<xsl:apply-templates select="year[not(../country='USA' and ../year='1985)]" />
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!我没有尝试过使用 not 函数。也感谢您提供有关逻辑的信息。到目前为止,我的很多错误似乎都与条件有关。 (2认同)