I want to fetch a data from xml Using Xquery with starts 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 fetch that name which has employee@id=title@id and name@value starts with 'vC'.
I have written this xquery for the same.Please see below but getting 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 error-
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)
starts-with()
function expects two parameters. I'm not familiar with Saxon specifically, but in general xquery you can do this way :
for $x in /data/employee[@id=title/@id and name[starts-with(@value,'vC')]]
return data($x/name)
or using where
clause instead of predicate in for
clause, as in your attempted query :
for $x in /data/employee
where $x/@id=$x/title/@id and $x/name/starts-with(@value,'vC')
return data($x/name)
Just use this shorter and simpler XPath 2.0 one-liner:
/*/employee[@id eq title/@id and starts-with(name/@value, 'vC')]/data(name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With