使用XPath和contains函数获取孙子节点的文本

3
我有以下XML。
<section level="sect1">
    <title>
      <page num="1150"/>
      <content-style font-style="bold">ORDER 62</content-style>
      <content-style format="smallcaps">Costs</content-style>
    </title>
</section>

我希望检查标题中是否含有单词ORDER

我已经尝试过:

contains(//section[1]/title[1]/content-style[1]/text(),'ORDER')

但是有些情况下字符串 ORDER 可能出现在第二个 content-style 中,或者有些情况下可能出现在第三个中。

请告诉我一种通用的查找方法。

谢谢。

4个回答

1
contains(//section[1]/title[1]/content-style[1]/text(),'ORDER')

你需要在整个路径上执行contains,明确指定在此表达式中使用[1]获取每个元素的第一个。根据你的描述,你想要的是具有"ORDER"的子content-style,你应该按照以下方式进行操作:
//section[1]/title[1]/content-style[text() = 'ORDER']

或者,如果可以添加空格:


//section[1]/title[1]/content-style[normalize-space(text()) = 'ORDER']

如果结果不为空,则表示您在任何title[1]下面、section[1]下面的任何content-style中至少找到了一个“ORDER”。
从祖父元素获取孙子元素的文本。
这是您的问题标题。它与您写的略有不同。如果您想检查来自“section”的任何孙子级content-style,请执行以下操作:
//section[1]/*/content-style[normalize-space(text()) = 'ORDER']



最后说明:您将原始问题标记为,在XSLT中,if条件不需要是布尔值,因此:


<xsl:if test="//section[1]/*/content-style[normalize-space(text()) = 'ORDER']">
    <hello>found it!</hello>
</xsl:if>

等同于将整个内容包裹在contains中,不同的是使用contains时您将检查由所有元素组合而成的字符串,这也将匹配例如'no such ORDER'


以上内容与以下类似:


<!-- in place of xsl;if -->
<xsl:apply-templates select="//section[1]/*/content-style" />

<!-- place this at root level anywhere -->
<xsl:template match="content-style[normalize-space(text()) = 'ORDER']">
    <hello>found it!</hello>
</xsl:template>

<xsl:template match="content-style">
    <hello>Not an order!</hello>
</xsl:template>

1
你想要
exists(//section[1]/title/content-style[contains(., 'ORDER')])

1

Here i want to check if the title has word ORDER in it.

I've tried

contains(//section[1]/title[1]/content-style[1]/text(),'ORDER')

but there are instances where the ORDER might be in 2nd content-style` or in some might be in 3rd.

please let me know a generic way of finding it.

这里有一个XPath 1.0表达式,可以准确生成所需的布尔值:
boolean((//section)[1]/title[1][content-style[contains(., 'ORDER')]])

这段代码在XML文档中的第一个
元素中,第一个title元素的子元素中至少有一个content-style元素时返回true()
对应的XPath 2.0表达式为:
exists((//section)[1]/title[1][content-style[contains(., 'ORDER')]])

0

我认为你需要获取“title”节点下方的所有文本。以下代码应该可以实现:

contains(//section[1]/title[1]/string(.),'ORDER')

至少根据这个参考


不,这并不相同,因为它还将包括page中的文本,title[1]中的任何混合内容以及可能在该级别的其他元素。 - Abel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接