XQuery路径表达式变量使用方法及路径左侧引入变量可行性
Hey there, let's tackle your two XQuery questions step by step—they're common gotchas when working with dynamic paths!
Using variables in path expressions is totally straightforward, and there are a few common ways to do it depending on what you need:
Filter nodes with variable values: If you have a variable holding a value to match, plug it into a predicate. For example, if
$dept-idstores a department ID you're targeting://department[@id = $dept-id]/employeeThis grabs all
employeenodes under thedepartmentwhoseidattribute matches$dept-id's value.Use variables as path starting points: If your variable references an existing node (not just a value), use it as the root of your path. Say
$selected-deptis a pre-querieddepartmentnode:$selected-dept/employee/nameThis pulls all
namenodes under employees in that specific department.Combine variables in nested paths: You can mix variables with complex paths too. If
$roleis set to "manager", try://employee[position/title = $role]/contact/email
The short answer is: No, you can't directly use a variable as a node name in the left side of a path (like //$emp_no). XQuery's path syntax requires node names to be static qualified names at parse time, so dynamic variable values can't replace them directly.
But there's an easy workaround using the node-name() function to dynamically match node names. Here's how to use it with your $emp_no variable (which holds the string "emp_no"):
To find all emp_no nodes anywhere in the document:
//*[node-name(.) = $emp_no]
To target only emp_no nodes that are children of employee nodes:
//employee/*[node-name(.) = $emp_no]
This works because node-name(.) returns the qualified name of the current node, and we compare it to the value in $emp_no. It gives you the same flexibility as using a variable directly in the path, while playing by XQuery's syntax rules.
内容的提问来源于stack exchange,提问作者Judah Flynn

