使用 XPath 从孙子那里获取文本并包含函数

Get text from a grand-child using XPath and contains function

我有以下 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>

这里我想检查 title 中是否有单词 ORDER

我试过了

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

但有些情况下字符串 ORDER 可能在第二个内容样式中,或者在某些情况下可能在第三个中。

请告诉我找到它的通用方法。

谢谢

我认为您需要从 "title" 节点下方获取所有文本。以下应该有效:

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

至少根据 this reference

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

你在整个路径上做一个contains,明确地说,在这个表达式中,用[1]得到每个元素的第一个。相反,根据您的描述,您想要 child content-style 其中包含 "ORDER",您应该按以下方式进行操作:

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

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

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

如果结果是non-empty,您在title[1]下方的任意content-stylesection[1]下方、[=29]下方至少找到了一个"ORDER" =]

get grand child text from grand parent element

这是你的问题标题。和你写的略有不同。如果你想从 section 检查 any grand-child content-style 然后这样做:

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

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

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

等于将整个内容包装在 contains 中,除了使用 contains 您将检查所有元素组合的字符串,这也将 mach '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>

你想要

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

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')]])

当至少有一个 content-style 元素是第一个 section 的第一个子元素的 title 元素的子元素时,这会产生 true() XML 文档中的元素。

和对应的 XPath 2.0 表达式:

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