2010-12-17 25 views
4

我正在嘗試編寫一個XQuery,它將查找包含xml文件中給定關鍵字的所有文本節點。文本節點很長,所以我想返回一個從匹配關鍵字開始的文本的子串(所需長度)。在XQuery中使用functx:index-of-match-first返回文本節點的子串

Samplefile.xml

<books> 
<book> 
    <title>linear systems</title> 
    <content>vector spaces and linear system analysis </content> 
</book> 
<book> 
    <title>some title</title> 
    <content>some content</content> 
</book> 
</books> 

samplexquery.xq

declare namespace functx = "http://www.functx.com"; 

for $match_result in /*/book/*[contains(.,'linear')]/text() 
    return substring($match_result, functx:index-of-match-first($match_result,'linear'), 50) 

我期望得到的結果[線性系統,線性系統的分析。第一本書的標題節點包含單詞'linear'。返回從'linear ....'開始的50個字符。對於第一本書的內容節點也是如此。

我使用XQuery 1.0和我包括命名空間fu​​nctx所示的例子中,在:http://www.xqueryfunctions.com/xq/functx_index-of-match-first.html

但是,這是給我一個錯誤:[XPST0017]未知功能「functx:索引的-匹配 - 第一(...)」。

感謝, 索尼

+0

好問題,+1。請參閱我的回答以獲得解釋和解決方案。 :) – 2010-12-17 19:47:44

回答

2

I am using XQuery 1.0 and I included the namespace functx as shown in the example at: http://www.xqueryfunctions.com/xq/functx_index-of-match-first.html

But, this is giving me an error: [XPST0017] Unknown function "functx:index-of-match-first(...)".

只聲明命名空間是不夠的。

您還必須擁有該函數的代碼。只有標準的XQuery and XPath functions and operators是預定義的語言。

該修正代碼

declare namespace functx = "http://www.functx.com"; 
declare function functx:index-of-match-first 
    ($arg as xs:string? , 
    $pattern as xs:string) as xs:integer? { 

    if (matches($arg,$pattern)) 
    then string-length(tokenize($arg, $pattern)[1]) + 1 
    else() 
} ; 

for $match_result in /*/book/*[contains(.,'linear')]/text() 
    return substring($match_result, functx:index-of-match-first($match_result,'linear'), 50) 

當所提供的XML文檔施加(具有校正的若干非良好性錯誤):

<books> 
    <book> 
    <title>linear systems</title> 
    <content>vector spaces and linear system analysis </content> 
    </book> 
    <book> 
    <title>some title</title> 
    <content>some content</content> 
    </book> 
</books> 

產生預期的結果

linear systems linear system analysis 

使用import module指令從現有函數庫導入模塊是一種很好的做法。

+0

哦,我認爲這些是預定義的功能。看起來他們是可重用的功能。非常感謝:) – sony 2010-12-17 19:51:49

+0

@sony:使用'import module'指令從現有的函數庫導入模塊是一個好習慣 – 2010-12-17 19:59:23

相關問題