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

Iss*_*ram 13 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>
Run Code Online (Sandbox Code Playgroud)

代码的最大部分是我认为我错了.在otherwise标签中需要一些东西,when我认为我的部分是错误的.

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

有人可以帮忙吗?先感谢您.

编辑:

是的,最后我至少需要一个<country />标签在XML中.但它是可能的,它并不存在于所有.如果它不存在,我必须把它放入.一个好的输入示例<country>US</country>

Mar*_*nen 12

在父元素的模板中,期望country元素正在使用中,例如

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

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


Dim*_*hev 12

更简单:

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

请注意:

没有XSLT条件指令(如<xsl:if>)使用,他们是没有必要的.

通常,存在<xsl:if><xsl:choose>表明代码可以通过除去其他方面的条件指令来重构和显着改进.


小智 6

您甚至不需要任何类型的条件处理.这个样式表:

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

有了这个输入:

<root>
    <item>
        <country>Brobdingnag</country>
    </item>
    <item>
        <test/>
    </item>
</root>
Run Code Online (Sandbox Code Playgroud)

输出:

<root>
    <item>
        <country>Brobdingnag</country>
    </item>
    <item>
        <test></test>
        <country>Lilliput</country>
    </item>
</root>
Run Code Online (Sandbox Code Playgroud)