2

I have an XML document:

<resultsets>
    <row>
        <emp_no>10001</emp_no>
        <first_name>Georgi</first_name>
        <last_name>Facello</last_name>
    </row>
    <row>
        <emp_no>10007</emp_no>
        <first_name>Bezalel</first_name>
        <last_name>Simmel</last_name>
    </row>
</resoutsets>

I have one variable query emp_no field defined as:

let $emp_no := doc("employees.xml")//emp_no

I want to use the $emp_no node name (emp_no) in my query to do the same thing, something like:

doc("employees.xml")//$emp_no/name()

Is it possible to involve a variable in the path on the left side of the expression?

Judah Flynn
  • 544
  • 1
  • 8
  • 20
  • What exactly are you trying to achieve? You can use variables in an XPath, but it doesn't really make much sense to select all of the elements with a particular name, and then execute another XPath to find all of the elements in the same document that have a name equal to the selected elements. The result would be the same elements already selected and assigned to the variable. – Mads Hansen Feb 18 '18 at 02:22

2 Answers2

4

Is it possible to involve a variable in the path on the left side of the expression?

The key point here is that replacing a name in a path with a variable reference is syntactically legal, but it doesn't mean what you probably think it means. If the variable $X has the value "orders", then

//customer/$X

doesn't mean

//customer/orders

Instead it means

//customer/"orders"

which returns one occurrence of the string "orders" for each customer element in the document.

If you want to find the elements whose name is equal to the string $X, use

//customer/*[name()=$X]

unless namespaces are involved, in which case you need to compare both namespace URI and local name.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
1

Yes, you can use variables in an XPath expression. But it is not clear what you are asking or trying to achieve.

If you were looking to select elements that have the same name() as those assigned to the elements assigned to the $emp_no variable, you could match any element and then use a predicate filter to test whether the name() is equal to any of the name() values from the sequence of elements in the $emp_no:

doc("employees.xml")//*[name() = $emp_no/name()]

However, that would just return the same emp_no elements that were already assigned to the $emp_no element.

Mads Hansen
  • 63,927
  • 12
  • 112
  • 147