Retrieving data from xml Using Xquery with launch with function

I want to get data from xml. Using Xquery with launch with function.

data.xml

<data><employee id=\"1\"><name value=\"vA-12\">A</name> <title id=\"2\">Manager</title></employee> <employee id=\"2\"><name value=\"vC-12\">C</name><title id=\"2\">Manager</title></employee> <employee id=\"2\"><name value=\"vB-12\">B</name><title id=\"2\">Manager</title></employee> </data> 

Now I want to get this name with the name employee @id = title @id, and name @value starts with 'vC'.

I wrote this xquery for the same. Please see below, but getting an error -

 for $x in /data/employee where $x/@id=$x/title/@id and [fn:starts-with($x/name/@value,vC)] return data($x/name) 

this is mistake -

  Error on line 1 column 55 XPST0003 XQuery syntax error near #.../title/@id and [fn:starts-with#: Unexpected token "[" in path expression net.sf.saxon.s9api.SaxonApiException: Unexpected token "[" in path expression at net.sf.saxon.s9api.XQueryCompiler.compile(XQueryCompiler.java:544) at Xml.process(Xml.java:46) at Xml.main(Xml.java:30) Caused by: net.sf.saxon.trans.XPathException: Unexpected token "[" in path expression at net.sf.saxon.query.XQueryParser.grumble(XQueryParser.java:479) at net.sf.saxon.expr.parser.XPathParser.grumble(XPathParser.java:221) 
+5
source share
3 answers
Function

starts-with() expects two parameters. I am not familiar with Saxon specifically, but in general xquery you can do this:

 for $x in /data/employee[@id=title/@id and name[starts-with(@value,'vC')]] return data($x/name) 

or using the where clause instead of the for predicate, as in your requested query:

 for $x in /data/employee where $x/@id=$x/title/@id and $x/name/starts-with(@value,'vC') return data($x/name) 
+3
source

Just use this shorter and simpler one-liner XPath 2.0 layer :

 /*/employee[@id eq title/@id and starts-with(name/@value, 'vC')]/data(name) 
+1
source

Depending on your exact requirements, you may need this (I let you figure out the differences, but basically it selects all names with @value starting with vC , where in other solutions here all names of all employees with the smallest name starting with vC ):

 /data/employee[@id eq title/@id]/name[starts-with(@value, 'vC')]/data(.) 
0
source

All Articles