XSLT:如果标签存在,应用模板;如果没有,请选择静态值 [英] XSLT: If tag exists, apply template; if not, choose static value

查看:20
本文介绍了XSLT:如果标签存在,应用模板;如果没有,请选择静态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to XSLT in general so please bear with me...

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

With that in mind, what I am trying to do is check for a certain tag in the XML. If it is there I want to apply a template. If not, I want to add it (as a blank value). Basically always forcing it to be in the final output. How would I do this?

我遇到过这样的事情...

I had something like this...

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

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

The top poriton of the code is what I think I have wrong. Need something in the otherwise tag and my when part is wrong i think.

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

有人可以帮忙吗?提前致谢.

Can anyone help? Thank you in advance.

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

Yes in the end i need at the very least a <country /> tag to be in the XML. But it is possible that it does not exist at all. If it doesn't exist, I have to put it in. An example good input would be <country>US</country>

推荐答案

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

In the template for the parent element the country element is expected to be in use e.g.

<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 不会对子元素执行任何操作不存在.

Instead of foo use the name of the parent element. And of course you could also do other stuff like copying the element, I have focused on the if check. You do not really need an xsl:choose/when/otherwise in my view, the xsl:if should suffice as the apply-templates will not do anything with child elements that don't exist.

这篇关于XSLT:如果标签存在,应用模板;如果没有,请选择静态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆