如何在Java上的Saxon中的XPath查询中设置变量

huangapple go评论83阅读模式
英文:

How do I set a variable in an XPath query in Saxon on Java

问题

以下代码返回 4 个节点(使用 southwind.xmlsouthwind.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(&quot;/windward-studios/Employees/Employee[@EmployeeID &lt; 5]&quot;);
XPathSelector selector = exec.load();
selector.setContextItem(datasource.getXmlRootNode());
XdmValue nodeSet = selector.evaluate();

But the following returns 0 nodes:

datasource.getxPathCompiler().declareVariable(new QName(&quot;p1&quot;));
XPathExecutable exec = datasource.getxPathCompiler().compile(&quot;/windward-studios/Employees/Employee[@EmployeeID &lt; p1]&quot;);
XPathSelector selector = exec.load();
selector.setContextItem(datasource.getXmlRootNode());
selector.setVariable(new QName(&quot;p1&quot;), new XdmAtomicValue(5));
XdmValue nodeSet = selector.evaluate();

What am I doing wrong?

Update:
It looks like it needs a $ sign:

compile(&quot;/windward-studios/Employees/Employee[@EmployeeID &lt; $p1]&quot;);

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.

huangapple
  • 本文由 发表于 2020年8月5日 03:06:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63253546.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定