如何在Xpath“contains()"中使用变量节点集功能 [英] How to use variable node-set in Xpath "contains()" function
问题描述
我想检查节点值是否包含出现在作为节点集的节点内变量的属性中的字符串.
I want to check if node value contains a string that occurs in an attribute of a node with-in variable made as a node-set.
<xsl:variable name="Var">
<root>
<tag atr="x3"> some string <tag>
<tag atr="x4"> some string <tag>
<root>
<xsl:variable>
xml 包含:
<name>one x3 two<name>
我尝试过类似的东西:
<xsl:value-of select="contains(name,msxsl:node-set($Var)/root/tag/@atr)"/>
但它只是输出什么,然后继续.
but it just output's nothing and move on.
推荐答案
在 XPath 1.0 中,如果一个函数或运算符需要一个字符串并被传递一个节点集,则只有第一个(按文档顺序)节点的字符串值节点集由该函数或运算符生成和使用.
In XPath 1.0 if a function or operator expects a string and is passed a node-set, only the string value of the first (in document order) node of the node-set is produced and used by this function or operator.
因此,表达式如:
contains(name, msxsl:node-set($Var)/root/tag/@atr)
只测试msxsl:node-set($Var)/root/tag/@atr
节点的第一个的字符串值是否包含在字符串中第一个 name
节点的值.
tests only whether the string value of the first of the msxsl:node-set($Var)/root/tag/@atr
nodes is contained in the string value of the first name
node.
您实际上想查看是否包含 msxsl:node-set($Var)/root/tag/@atr
中的 any 节点的字符串值在一个给定元素的字符串值中,命名为 name
.
You actually want to see if the string value of any of the nodes in msxsl:node-set($Var)/root/tag/@atr
is contained in a the string value of a given element, named name
.
评估这个条件的一个正确的 XPath 表达式:
boolean(msxsl:node-set($Var)/root/tag/@atr[contains($name, .)])
其中 $name
被定义为包含元素 name
.
where $name
is defined to contain exactly the element name
.
完整的代码示例:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="name" select="'x42'"/>
<xsl:variable name="Var">
<root>
<tag atr="x3"> some string </tag>
<tag atr="x4"> some string </tag>
</root>
</xsl:variable>
<xsl:template match="/">
<xsl:value-of select=
"boolean(msxsl:node-set($Var)
/root/tag/@atr[contains($name, .)])"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于任何 XML 文档(未使用)时,会产生所需的正确结果:
true
但是,如果我们在上述转换中替换另一个答案中提供的 XPath 表达式(由 Siva Charan):
However, if we substitute in the above transformation the XPath expression offered in the another answer (by Siva Charan) :
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:variable name="name" select="'x42'"/>
<xsl:variable name="Var">
<root>
<tag atr="x3"> some string </tag>
<tag atr="x4"> some string </tag>
</root>
</xsl:variable>
<xsl:template match="/">
<xsl:value-of select=
"contains(name, msxsl:node-set($Var)/root/tag/@atr)"/>
</xsl:template>
</xsl:stylesheet>
这个转换产生了错误的答案:
false
因为它只测试包含所有 attr
属性中的第一个属性.
because it only tests for containment the first of all attr
attributes.
这篇关于如何在Xpath“contains()"中使用变量节点集功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!