英文:
How do I set a variable in an XPath query in Saxon on Java
问题
以下代码返回 4 个节点(使用 southwind.xml 和 southwind.xsd):
XPathExecutable exec = datasource.getxPathCompiler().compile("/windward-studios/Employees/Employee[@EmployeeID < 5]");
XPathSelector selector = exec.load();
selector.setContextItem(datasource.getXmlRootNode());
XdmValue nodeSet = selector.evaluate();
但以下代码返回 0 个节点:
datasource.getxPathCompiler().declareVariable(new QName("p1"));
XPathExecutable exec = datasource.getxPathCompiler().compile("/windward-studios/Employees/Employee[@EmployeeID < p1]");
XPathSelector selector = exec.load();
selector.setContextItem(datasource.getXmlRootNode());
selector.setVariable(new QName("p1"), new XdmAtomicValue(5));
XdmValue nodeSet = selector.evaluate();
我做错了什么?
更新:
看起来需要加上一个 $ 符号:
compile("/windward-studios/Employees/Employee[@EmployeeID < $p1]");
这样正确吗?
英文:
The following code returns 4 nodes (using southwind.xml & southwind.xsd):
XPathExecutable exec = datasource.getxPathCompiler().compile("/windward-studios/Employees/Employee[@EmployeeID < 5]");
XPathSelector selector = exec.load();
selector.setContextItem(datasource.getXmlRootNode());
XdmValue nodeSet = selector.evaluate();
But the following returns 0 nodes:
datasource.getxPathCompiler().declareVariable(new QName("p1"));
XPathExecutable exec = datasource.getxPathCompiler().compile("/windward-studios/Employees/Employee[@EmployeeID < p1]");
XPathSelector selector = exec.load();
selector.setContextItem(datasource.getXmlRootNode());
selector.setVariable(new QName("p1"), new XdmAtomicValue(5));
XdmValue nodeSet = selector.evaluate();
What am I doing wrong?
Update:
It looks like it needs a $ sign:
compile("/windward-studios/Employees/Employee[@EmployeeID < $p1]");
Is that correct?
答案1
得分: 0
XPath 和 XSLT 中的变量引用以 $
开头,所以在 XPath 中引用名为 p1
的变量的正确方式是 $p1
。你之前尝试的 p1
会选择一个名为 p1
的元素节点。
英文:
Variable references in XPath and XSLT start with $
, so $p1
is the right way in XPath to reference the variable named p1
. Your previous attempt p1
would select an element node named p1
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论