3

我正在使用 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

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

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

谢谢,索尼

4

2 回答 2

2
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>
于 2011-05-22T19:01:16.250 回答
1

对于您的问题 1 - 您可以尝试使用 fn:data() 从 Xml 特定事物中转义所有用户输入值。

对于您的问题 2 - 如果您使用任何 Xml 数据库尝试利用数据库搜索 API 而不是 Xpath。如果不是,您需要提出一些定义的抽象 xquery 搜索层,它可以形成 XPath 语法,而不是直接通过 xpath。

于 2011-05-22T13:17:26.340 回答