XSLT:如果标签存在,请应用模板;如果没有,请选择静态值

时间:2011-04-26 13:27:21

标签: xml xslt xslt-2.0 xslt-1.0

我是XSLT的新手,所以请耐心等待......

考虑到这一点,我要做的是检查XML中的某个标记。如果它在那里我想要应用模板。如果没有,我想添加它(作为空白值)。基本上总是强迫它在最终输出中。我该怎么做?

我有这样的事情......

<xsl:choose>
    <xsl:when test="@href">
        <xsl:apply-templates select="country" />
    </xsl:when>
    <xsl:otherwise>
    </xsl:otherwise>
</xsl:choose>

代码的最大部分是我认为我错了。在otherwise标记中需要一些内容,而我认为我的when部分是错误的。

<xsl:template match="country">
    <xsl:if test=". != '' or count(./@*) != 0">
        <xsl:copy-of select="."/>
    </xsl:if>
</xsl:template>

有人可以帮忙吗?提前谢谢。

编辑:

是的,最后我需要至少一个<country />标记在XML中。但它可能不存在根本。如果它不存在,我必须把它放进去。一个好的输入示例是<country>US</country>

3 个答案:

答案 0 :(得分:12)

在父元素的模板中,国家元素应该在使用中,例如

<xsl:template match="foo">
  <xsl:if test="not(country)">
    <country>US</country>
  </xsl:if>
  <xsl:apply-templates/>
</xsl:template>

而不是foo使用父元素的名称。当然你也可以做其他的事情,比如复制元素,我专注于if检查。您在我的视图中并不需要xsl:choose/when/otherwisexsl:if应该足够,因为apply-templates不会对不存在的子元素执行任何操作。

答案 1 :(得分:12)

更简单

<xsl:template match="foo[not(country)]">
        <country>US</country>
    <xsl:apply-templates/>
</xsl:template>

请注意

没有使用XSLT条件说明(例如<xsl:if> ,并且它们不是必需的。

通常情况下,<xsl:if><xsl:choose>的存在表明代码可以通过除去条件指令等方式进行重构和显着改进。

答案 2 :(得分:6)

你甚至不需要任何Conditional Processing。这个样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="item[not(country)]">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
            <country>Lilliput</country>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

使用此输入:

<root>
    <item>
        <country>Brobdingnag</country>
    </item>
    <item>
        <test/>
    </item>
</root>

输出:

<root>
    <item>
        <country>Brobdingnag</country>
    </item>
    <item>
        <test></test>
        <country>Lilliput</country>
    </item>
</root>
相关问题