部分字符串搜索 XQuery / XPath(如 SQL 中的 LIKE 语句)

Partial string search XQuery / XPath (As the LIKE statement in SQL)

使用 SQL 如果您只知道部分值,则可以使用 LIKE 语句获取结果。但是在 XQuery 中,我似乎无法找到一种方法来以同样的方式搜索我的 XML 文件。

这是我试过但不起作用的方法:

for $c in /parent/child  where $c/element="*partial strin*" return $c/element
for $c in /parent/child  where $c/element="%partial strin%" return $c/element

您应该看看 Starts-with() 和 Contains() 函数,它们都可以进行部分搜索。鉴于您上面的示例,这将是

//parent/child[contains(@element, 'partial stri')]

注意我假定@element 是子元素的一个属性,如果您只想搜索子元素的文本,请将@element 替换为单个“.”

实际上您根本不需要 for 表达式,您可以只使用谓词。对于精确的子字符串匹配,有 contains 函数:

/parent/child/element[contains(., "partial strin")]

对于更复杂的匹配,您可以使用带有 matches 函数的正则表达式:

/parent/child/element[matches(., "^partial\s+strin")]