Java – XPath multi tag selection
•
Java
For a given XML, how do I use XPath to select C, D, G, H (this will be a child tag in B that is not 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>
I want to use the following to get the result, but it doesn't give me g, H values
xpath.compile("//a/b/*[self::c or self::d or self::f/text()");
The Java code I use
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()); } }
}
Who can help me with this?
Thank you.
Solution
use:
//a/b/*[not(self::e or self::f)] | //a/b/*/*[self::g or self::h]
If you have a good understanding of the structure of an XML document and / / the only descendants a / B can have are g and / or h, this can be simplified as:
//a/b/*[not(self::e or self::f)] | //a/b/*/*
In XPath 2.0, this can be written more simply:
//a/b/(*[not(self::e or self::f)] | */*)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码