0

I know how to select an element like so:

$table/foo

However how do I do this if the element name is stored as a variable. For example:

let $x = "foo"
$table/[$x]

I know how do this if it was a property from: How to select an attribute by a variable in xquery?

Community
  • 1
  • 1
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231

2 Answers2

2

This is nearly identical to the answer for the question How to select an attribute by a variable in xquery? but instead of using the attribute selector @*, you would use the element selector, * (or element()):

$table/*[local-name() = 'foo']

$table/element()[local-name() = 'foo']
Community
  • 1
  • 1
wst
  • 11,681
  • 1
  • 24
  • 39
  • which is more likely to be more efficient `*` or `element()` – Yahya Uddin Dec 01 '15 at 17:32
  • 1
    @YahyaUddin They are equivalent. You can think of `*` as a "macro" for `element()`. – wst Dec 01 '15 at 19:25
  • Would this still work if the element name was more complex like "foo/bar/hat" – Yahya Uddin Dec 01 '15 at 19:45
  • 1
    @YahyaUddin Yes, in every case these are essentially just evaluating expressions and subexpressions. Similar to the star expression, `foo/bar` is shorthand for `element(foo)/child::element(bar)`. You can continue to walk the tree indefinitely as long as your expressions are valid. – wst Dec 01 '15 at 20:11
1

Would this still work if the element name was more complex like "foo/bar/hat"

No, the predicate [name() = 'foo/bar/hat'] would not select anything, because foo/bar/hat is a path expression, not an element name. Variables in XPath hold values, not expressions or expression fragments - it's not like a shellscript (or other macro language) where variables are expanded and the expanded expression is then re-parsed.

XQuery does not have any general capability for constructing an expression dynamically as a string and then evaluating it. Many products have extension functions to do this, often called xx:eval() or xx:evaluate(). XSLT 3.0 has an xsl:evaluate instruction.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • I have rolled back the edits. That kind of typography might look good in Chennai, but it's not my style, and I reserve the right to write in my own style without some copy-editor changing it to suit theirs. – Michael Kay Jul 07 '16 at 08:33