对于给定的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());
}
}
有人能帮我吗?
非常感谢!!!
/
。 - Emiliano Poggi