java xpath how to get all data different of specific node

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

java xpath how to get all data different of specific node

问题

我想获取除了节点“car”之外的所有节点。

XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xpath.evaluate("//car[not(self::node())]", document, XPathConstants.NODESET);

如何设置类似于:

NodeList nodes = (NodeList) xpath.evaluate("//*[not(self::car)]", document, XPathConstants.NODESET);
英文:

I would like to get all nodes different of node car.

XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xpath.evaluate("//car", document, XPathConstants.NODESET);

How to set something like :

NodeList nodes = (NodeList) xpath.evaluate(!"//car", document, XPathConstants.NODESET);

答案1

得分: 1

XPath字符串前面添加感叹号是无效的。确实,对于Java来说,XPath表达式只是一个字符串:它的内容不会被Java本身解释,而是由你正在使用的XPath库来解释。

因此,这里唯一的解决方案是修改String内部的XPath表达式。

你可以按照以下方式进行:

NodeList nodes = (NodeList) xpath.evaluate("//*[name() != 'car']", document, XPathConstants.NODESET);

解释: //*[name() != 'car'] 意味着:查找文档中所有节点名称不是'car'的节点。

英文:

Adding an exclamation mark in front of the XPath string does not work. Indeed, for Java, the XPath expression is just a String: its content will not be interpreted by Java itself, but by the XPath library you are using.

Therefore, the only solution here is to modify the XPath expression inside the String.

You can do it as follows:

NodeList nodes = (NodeList) xpath.evaluate("//*[name() != 'car']", document, XPathConstants.NODESET);

Explanation: //*[name() != 'car' means : find all nodes in the document whose name is not 'car'

huangapple
  • 本文由 发表于 2020年9月16日 22:18:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63922059.html
匿名

发表评论

匿名网友

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

确定