XSl:Variable - 检查值是否存在的条件 [英] XSl:Variable - Condition to check whether value exist

查看:48
本文介绍了XSl:Variable - 检查值是否存在的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 XSLT 1.0,如何检查变量中的值是否存在?

Using XSLT 1.0, how do I check whether the value in the variable exists or not?

我最初从我的 XML 数据将值分配给变量,然后需要检查它是否存在:

I am assigning the value to the variable initially from my XML data and then need to check whether it exits or not:

<xsl:variable name="DOC_TYPE">
  <xsl:value-of select="name(./RootTag/*[1])"/>
</xsl:variable>
<xsl:if test="string($DOC_TYPE) = ''">
  <xsl:variable name="DOC_TYPE">
    <xsl:value-of select="name(./*[1])"/>
  </xsl:variable>
</xsl:if>  

以上没有按预期工作.我需要的是,如果 存在于我的数据中,那么该变量应包含 下方的子节点.如果 不存在,那么 DOC_TYPE 应该是我的 XML 数据中的第一个标签.

The above is not working as expected. What I need is if <RootTag> exists in my data then the variable should contain the child node below the <RootTag>. If <RootTag> does not exist then the DOC_TYPE should be the first Tag in my XML data.

感谢您的回复.

推荐答案

您不能在 XSLT 中重新分配变量.变量是不可变的,你不能改变它们的值.曾经.

You can't re-assign variables in XSLT. Variables a immutable, you can't change their value. Ever.

这意味着您必须变量声明中决定它将具有什么值:

This means you must decide within the variable declaration what value it is going to have:

<xsl:variable name="DOC_TYPE">
  <xsl:choose>
    <xsl:when test="RootTag">
      <xsl:value-of select="name(RootTag/*[1])" />
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="name(*[1])" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:variable>

其他一些注意事项:

  • this: './RootTag' 是多余的.默认情况下,每个不以斜杠开头的 XPath 都是相对的,所以说 'RootTag' 就足够了
  • this: <xsl:value-of select="name(*[1])"/> 已经产生了一个字符串(名称根据定义是字符串),所以没有需要做 <xsl:if test="string($DOC_TYPE) = ''"> ,一个简单的 ; 就够了
  • 要检查节点是否存在,只需在 test="..." 表达式中通过 XPath 选择它 - 任何非空节点集的计算结果为 true
  • XSLT 有严格的范围规则.变量仅在其父元素内有效.您的第二个变量(<xsl:if> 中的那个)将立即超出范围(意味着就在 </xsl:if>).
  • this: './RootTag' is redundant. Every XPath you don't start with a slash is relative by default, so saying 'RootTag' is enough
  • this: <xsl:value-of select="name(*[1])"/> already results in a string (names are strings by definition), so there is no need to do <xsl:if test="string($DOC_TYPE) = ''"> , a simple <xsl:if test="$DOC_TYPE = ''"> suffices
  • to check if a node exists simply select it via XPath in a test="..." expression - any non-empty node-set evaluates to true
  • XSLT has strict scoping rules. Variables are valid within their parent elements only. Your second variable (the one within the <xsl:if>) would go out of scope immediately(meaning right at the </xsl:if>).

这篇关于XSl:Variable - 检查值是否存在的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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