Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XQuery return text node if it contains given keyword

Tags:

xpath

xquery

A test sample of my xml file is shown below:

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>

Now, I want to write an xquery which will find all <entry> elements which have <libx:libapp> as a child. Then, for all such entries return the title if the title contains a given keyword (such as Link). So, in my example xml document the xquery should return "Link ISBN".

My sample xquery is shown below:

samplequery.xq (here doc_name is the xml file shown above and libapp_matchkey is a keyword such as 'Link')

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

This xquery is returning null instead of the expected result 'Link ISBN'. Why is that?

like image 325
sony Avatar asked Feb 25 '23 14:02

sony


1 Answers

I want to write an xquery which will find all elements which have as a child. Then, for all such entries return the title if the title contains a given keyword (such as Link).

Just use:

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

Wrapping this XPath expression in XQuery we get:

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

when applied on the provided XML document:

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

the wanted, correct result is produced:

Link ISBN
like image 176
Dimitre Novatchev Avatar answered Mar 24 '23 08:03

Dimitre Novatchev