对于给定的 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>
我想过使用 following 来获取结果,但它没有给我 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());
}
}
谁能帮我解决这个问题?
非常感谢!!!
最佳答案
如果要选择所有 c、d、g、h 节点,请使用此 xpath:
"//c|//d|//g|//h"
如果你想指定从根开始的完整路径,使用这个:
"/a/b/c|/a/b/d|/a/b/f/g|/a/b/f/h"
或者如果你想要 b 内的所有 c、d、g 或 h:
"//b//c|//b//d|//b//g|//b//h"
此外,在您的代码中:使用 nodes.item(i).getTextContent()
而不是 GetNodeValue。
关于java - xpath多标签选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6530770/