IT干货网

xml之xquery:跨可变节点集搜索

sharpest 2025年05月04日 编程设计 231 0

我正在使用 BaseX XML 数据库。考虑数据库中的 xml 文档,如下所示:

<entries> 
<book-entry> 
  <book>Book 1</book> 
  <author>Author 1 ABC</author> 
  <title>Title 1</title> 
</book-entry> 
<car-entry> 
  <car>Car 1</car> 
  <model>Model 1</model> 
  <price>Price 1 ABC</price> 
</car-entry> 
</entries> 

我正在尝试使用不同的选项执行搜索,例如:仅搜索书籍、仅搜索汽车、书籍和汽车。

我正在尝试在我的 xquery 中使用一个 xml 变量,以根据所需的搜索类型返回搜索结果。

示例变量值: - <types><type>book-entry</type></types> :仅搜索书籍条目 - <types><type>car-entry</type></types> :仅搜索汽车条目 - <types><type>book-entry</type><type>car-entry</type></types> : 搜索书籍条目和汽车条目

XQuery 示例:

declare variable $doc_name as xs:string external; (: name of xml document :) 
declare variable $search_types as xs:anyAtomicType external; (: one of the example variable values shown above :) 
declare variable $search_key as xs:string external; (: eg: ABC :) 
 
for $entry in doc($doc_name)/entries[*[exists($search_types/types/type/text() = node-name(.)) and .//text() contains text $search_key]] 
  return $entry 

尽管我通过了 <types><type>car-entry</type></types>,但上面的查询返回了包含文本子节点 ABC 的汽车和书籍条目。到 $search_types。

如何使用 xml 变量限制搜索?有更好的方法吗?此外,如果 xml 变量具有两种类型的子节点,则 xquery 必须同时返回汽车和条目。

谢谢, 索尼

请您参考如下方法:

for $entry in doc($doc_name)/entries 
         [*[exists($search_types/types/type/text() = node-name(.))  
        and  
          .//text() contains text $search_key 
           ] 
         ]  return $entry 

必须是:

for $entry in doc($doc_name)/entries/* 
        [exists($search_types/types/type/text() = node-name(.))  
       and  
         .//text() contains text $search_key]   
  return $entry 

或者,也可以使用这个简单的 XPath 表达式:

/*/*[name() eq $vSearchTypes/types/type 
   and 
     .//text()[contains(., $vSearchKey)] 
    ] 

最后,这个 XQuery 表达式:

let $vSearchTypes := 
  <types> 
    <type>book-entry</type> 
</types>, 
 
$vSearchKey := 'ABC' 
 
return 
  /*/*[name(.) eq $vSearchTypes/type 
        and 
          .//text()[contains(., $vSearchKey)] 
         ] 

应用于提供的 XML 文档时:

<entries> 
  <book-entry> 
    <book>Book 1</book> 
    <author>Author 1 ABC</author> 
    <title>Title 1</title> 
  </book-entry> 
  <car-entry> 
    <car>Car 1</car> 
    <model>Model 1</model> 
    <price>Price 1 ABC</price> 
  </car-entry> 
</entries> 

产生想要的、正确的结果:

<book-entry> 
    <book>Book 1</book> 
    <author>Author 1 ABC</author> 
    <title>Title 1</title> 
  </book-entry> 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!