我正在使用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必须返回汽车和条目。
谢谢, 索尼
答案 0 :(得分:1)
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>
答案 1 :(得分:0)
对于你的问题1 - 你可以尝试用fn:data()来逃避特定于Xml的所有用户输入值。
问题2的- 如果您使用任何Xml数据库尝试利用数据库搜索API而不是Xpath。如果不是你需要提出一些定义的抽象xquery搜索层,它可以形成XPath语法,而不是直接通过xpath。