【问题标题】:XSL Apply template with ORXSL 使用 OR 应用模板
【发布时间】:2014-08-26 11:40:01
【问题描述】:

我想应用一个模板,但只适用于第一个匹配项。假设我有一个像这样的 xml:

<cd>
    <title>Red</title>
    <artist>The Communards</artist>
    <country>UK</country>
    <company>London</company>
    <price>7.80</price>
    <year>1987</year>
</cd>
<cd>
    <artist>Joe Cocker</artist>
    <country>USA</country>
    <company>EMI</company>
    <price>8.20</price>
    <year>1987</year>
</cd>

请注意,第二张 CD 没有标题节点。 和 xsl:

<xsl:template match="title">
  Title: <xsl:value-of select="."/><br/>
</xsl:template>

<xsl:template match="artist">
  Artist: <xsl:value-of select="."/><br/>
</xsl:template>

如果有节点标题,我想应用该模板,否则我想为艺术家应用模板。我正在尝试类似

<xsl:apply-templates select="title | artist"/>

但是它会同时使用这两个,我只希望应用第一个。因此,如果有标题,请使用该标题,否则使用艺术家。是否可以通过这种方式或仅使用&lt;xsl:choose&gt; 来完成?

【问题讨论】:

  • match="artist[not(preceding-sibling::title or following-sibling::title)]"?
  • @biziclop 这意味着 XML 始终处于相同的顺序,(在我的情况下)它不是。或者至少我不能依赖它。
  • 不,这意味着艺术家模板只有在没有名为 title 的(之前或之后的)兄弟姐妹时才会匹配。它相当于artist[not(../title)],但更好地展示了这个想法。
  • @biziclop 你是对的,对不起。我认为它必须是直接在之前或之后。

标签: xml xslt


【解决方案1】:

如果有节点标题我想应用该模板,否则我 想要为艺术家应用模板。

写一个匹配title的模板

<xsl:template match="title">

另一个artist,假设它的父节点没有子title元素。

<xsl:template match="artist[not(../title)]">

假设输入正确(您显示的 XML 格式不正确,因为没有单个文档元素),您可以应用下面的样式表。

样式表

如果您的样式表输出文本,建议将其放在xsl:text 元素中。

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="text" encoding="UTF-8" indent="yes" />

    <xsl:template match="title">
      <xsl:text>Title: </xsl:text>
      <xsl:value-of select="."/>
      <xsl:text>&#10;</xsl:text>
    </xsl:template>

    <xsl:template match="artist[not(../title)]">
        <xsl:text>Artist: </xsl:text>
        <xsl:value-of select="."/>
        <xsl:text>&#10;</xsl:text>
    </xsl:template>

    <xsl:template match="text()"/>
</xsl:transform>

XML 输出

Title: Red
Artist: Joe Cocker

【讨论】:

  • 完美!我用这个
  • @Nin 你可以,但是你也必须改变这个模板的内容,因为你需要在模板内部决定是否应该输出“标题:”或“艺术家:”。跨度>
  • 这应该很简单,使用&lt;text&gt;&lt;xsl:value-of select="local-name()"/&gt;&lt;/text&gt;
  • @michael.hor257k 完全正确,首字母大写。
  • 这只是一个示例 xml,我并没有真正从事 CD 目录项目;)
【解决方案2】:

试试:

 <xsl:apply-templates select="(title | artist)[1]"/>

注意使用select 而不是matchxsl:apply-templates 元素没有 match 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2014-03-18
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多