java – xpath多标记选择
发布时间:2020-12-15 05:06:24 所属栏目:Java 来源:网络整理
导读:对于给定的 XML,我如何使用xpath选择c,d,g,h(这将是b中不是j的子标签)? XML a b cselect me/c dselect me/d edo not select me/e f gselect me/g hselect me/h /f /b j cselect me/c dselect me/d edo not select me/e f gselect me/g hselect me/h /f /j/a
|
对于给定的
XML,我如何使用xpath选择c,d,g,h(这将是b中不是j的子标签)?
XML <a>
<b>
<c>select me</c>
<d>select me</d>
<e>do not select me</e>
<f>
<g>select me</g>
<h>select me</h>
</f>
</b>
<j>
<c>select me</c>
<d>select me</d>
<e>do not select me</e>
<f>
<g>select me</g>
<h>select me</h>
</f>
</j>
</a>
我想使用以下来获取结果,但它没有给我g,h值 xpath.compile("//a/b/*[self::c or self::d or self::f/text()");
我使用的java代码 import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class XPathDemo {
public static void main(String[] args)
throws ParserConfigurationException,SAXException,IOException,PathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("test.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//a/b/*[self::c or self::d or self::f]/text()");
Object result = expr.evaluate(doc,XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
} 谁能帮我这个? 非常感谢!!! 解决方法
使用:
//a/b/*[not(self::e or self::f)] | //a/b/*/*[self::g or self::h] 如果你很好地了解XML文档的结构,并且// a / b可以拥有的唯一的子孙是g和/或h,那么这可以简化为: //a/b/*[not(self::e or self::f)] | //a/b/*/* 在XPath 2.0中,这可以写得更简单: //a/b/(*[not(self::e or self::f)] | */*) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
