|
>Home>Learn XQuery> XQuery Tips and Tricks>Variables in XPath
Print
Can I use variables in my XPath expressions?
If we run the following XQuery:
let $xml := <root><book>book1</book><video>video1</video></root>
for $el in ("book", "video")
return $xml/$el/text()
... we get this error:
It is a type error if the result of a step (other than the last step) in a path expression contains an atomic value.
The problem is that $el is being inserted in the XPath expression as a string literal, not as the name of an element; it as if you tried to run an XPath expression like $xml/”book”/text().
What you typically are trying to do is:
let $xml := <root><book>book1</book><video>video1</video></root>
for $el in ("book", "video")
return $xml/*[local-name() eq $el]/text()
Next Question!
How do I choose the right comparison operator?
|