Using functx: index-of-match-first in XQuery to return a substring of text node

I am trying to write XQuery that will find all text nodes that contain the given keyword in an XML file. The text node is long, so I would like to return a substring (of the desired length) of the text, starting with the corresponding keyword.

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) 

I expect to get the result [linear systems, linear systems analysis]. The node name of the first book contains the word "linear". Return 50 characters starting with 'linear ....'. Similarly for the content node of the first book.

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

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

Thanks Sony

+4
source share
1 answer

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

But this gives me an error: [XPST0017] Unknown function. "Functx: index-of-match-first (...)"

Simply declaring a namespace is not enough.

You must also have a function code. Only standard XQuery and XPath functions and operators are predefined in the language.

This corrected code :

 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) 

when applied to the provided XML document (with the correction of several incorrect errors):

 <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> 

gives the expected result :

 linear systems linear system analysis 

It is recommended that you use the import module directive to import modules from existing function libraries .

+2
source

Source: https://habr.com/ru/post/1332541/


All Articles