使用XSL 1.0有条理地包装内容

时间:2013-01-09 22:02:37

标签: xml xslt xslt-1.0

我正在寻找一种用xsl包装内容的方法。这是我正在做的简化示例。内容的批次...是大量内容,锚标记仅用作示例。它可能是一个div或其他任何东西。

XML:

<root>
    <attribution>John Smith</attribution>
    <attributionUrl>http://www.johnsmith.com</attributionUrl>
</root>

XSL:我目前是怎么做的。这增加了大量的xsl,我确信有一种简化的方法。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
    <xsl:if test="attribution != ''">
        <xsl:choose>
            <xsl:when test="attributionUrl != ''">
                <a>
                    <xsl:attribute name="href"><xsl:value-of select="attributionUrl"/></xsl:attribute>
                    <span>Thank you, <xsl:value-of select="attribution"/></span>
                    <div>Lots of content ...</div>
                </a>
            </xsl:when>
            <xsl:otherwise>
                <span>Thank you, <xsl:value-of select="attribution"/></span>
                    <div>Lots of content ...</div>
            </xsl:otherwise>
        </xsl:choose>   
    </xsl:if>
</xsl:template>

XSL:从概念上讲,这就是我想要做的。它不起作用,因为它是无效的XML,但它确实捕获了这个想法。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
    <xsl:if test="attributionUrl != ''">
        <a>
    </xsl:if>

    <xsl:attribute name="href"><xsl:value-of select="attributionUrl"/></xsl:attribute>
    <span>Thank you, <xsl:value-of select="attribution"/></span>
    <div>Lots of content ...</div>

    <xsl:if test="attributionUrl != ''">
        </a>
    </xsl:if>
</xsl:template>

编辑:

我正在尝试避免使用<div>Lots of content ...</div>

的多个版本

2 个答案:

答案 0 :(得分:1)

您可以拥有一个模板来执行“谢谢”的操作并将其用于两种情况。无论如何,使用模板匹配代替<xsl:if><xsl:when>更符合XML的精神:

<xsl:template match="root[attributionUrl!='']">
  <a href="{attributionUrl}">
    <xsl:call-template name="thankYou"/>
  </a>
</xsl:template>

<xsl:template match="root" name="thankYou">
  <span>Thank you, <xsl:value-of select="attribution"/></span>
  <div>Lots of content ...</div>
</xsl:template>

答案 1 :(得分:1)

这应该这样做:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="text()" />

  <xsl:template match="root[attributionUrl !='' and attribution != '']">
    <a href="{attributionUrl}">
      <xsl:apply-templates select="attribution" />
    </a>
  </xsl:template>

  <xsl:template match="attribution[. != '']">
    <span>
      Thank you, <xsl:value-of select="attribution"/>
    </span>
    <div>Lots of content ...</div>
  </xsl:template>
</xsl:stylesheet>