2010-12-14 28 views
4

我的XML文件的測試樣品如下:的XQuery返回文本節點是否包含特定關鍵字

的test.xml

<feed> 
    <entry> 
    <title>Link ISBN</title> 
    <libx:libapp xmlns:libx="http://libx.org/xml/libx2" /> 
    </entry> 
    <entry> 
    <title>Link Something</title> 
    <libx:module xmlns:libx="http://libx.org/xml/libx2" /> 
    </entry> 
</feed> 

現在,我想寫一個XQuery,將發現所有<entry>作爲孩子有<libx:libapp>的元素。然後,如果標題包含給定關鍵字(例如鏈接),則對於所有這些條目返回標題。所以,在我的xml文檔中,xquery應該返回「Link ISBN」。

我的示例XQuery是如下所示:

samplequery.xq(這裏是DOC_NAME上面所示的XML文件,並libapp_matchkey是一個關鍵字,例如 '鏈接')

declare namespace libx='http://libx.org/xml/libx2'; 
declare variable $doc_name as xs:string external; 
declare variable $libpp_matchkey as xs:string external; 
let $feeds_doc := doc($doc_name) 

for $entry in $feeds_doc/feed/entry 
    (: test whether entry has libx:libapp child and has "Link" in its title child :) 
    where ($entry/libx:libapp and $entry/title/text()[contains(.,$libapp_matchkey)]) 
    return $entry/title/text() 

該XQuery是返回null而不是預期的結果'鏈接ISBN'。這是爲什麼?

+0

我已經更換了'$ food_doc'聲明爲'/',糾正了'$ libapp_matchkey'錯字,併成功地與輸入樣本拼命地跑它。 – 2010-12-14 21:43:31

+0

好問題,+1。 – 2010-12-14 22:14:57

回答

6

我想寫一個xquery,它將 找到所有具有 作爲孩子的元素。然後,對於 ,如果標題包含給定關鍵字 (如鏈接),則所有此類條目都將返回標題。

只需使用

/*/entry[libx:libapp]/title[contains(.,'Link')]/text() 

包裝這個XPath表達式XQuery中,我們得到

declare namespace libx='http://libx.org/xml/libx2'; 
/*/entry[libx:libapp]/title[contains(.,'Link')]/text() 

時所提供的XML文檔應用:

<feed> 
    <entry> 
    <title>Link ISBN</title> 
    <libx:libapp xmlns:libx="http://libx.org/xml/libx2" /> 
    </entry> 
    <entry> 
    <title>Link Something</title> 
    <libx:module xmlns:libx="http://libx.org/xml/libx2" /> 
    </entry> 
</feed> 

想要的,正確的結果產生

Link ISBN 
+0

我看到下面的例外情況,當我嘗試這樣做:$ feed_doc/atom中的$ entry:feed/atom:entry return/*/$ entry [libx:libapp]/title [contains(。,'Link')]/text()線程「main」中的異常java.io.IOException:在第9行第13列處停止:[XPDY0002]沒有爲「root()」設置上下文項目。 – sony 2010-12-14 22:39:56

+0

@sony:在我的答案中沒有任何'$ entry' - 你可能在任何不是我的答案的東西上得到任何可能的例外,但你爲什麼要在這裏報告這個評論? – 2010-12-14 22:40:01

+1

/*是指什麼?我的意思是入口元素在文檔中的元素內。你是指什麼$ feeds_doc/feed – sony 2010-12-14 22:43:51

相關問題