Java 如何在 Saxon 的 XPath 查询中设置变量
How do I set a variable in an XPath query in Saxon on Java
以下代码returns4个节点(使用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();
但以下 returns 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]");
对吗?
XPath 和 XSLT 中的变量引用以 $
开头,因此 $p1
是 XPath 中引用名为 p1
的变量的正确方法。您之前的尝试 p1
将 select 一个名为 p1
.
的元素节点
以下代码returns4个节点(使用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();
但以下 returns 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]");
对吗?
XPath 和 XSLT 中的变量引用以 $
开头,因此 $p1
是 XPath 中引用名为 p1
的变量的正确方法。您之前的尝试 p1
将 select 一个名为 p1
.