英文:
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'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论