xpath多标签选择

Pav*_*ara 3 java xml xpath xml-parsing

对于给定的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>
Run Code Online (Sandbox Code Playgroud)

我想使用以下来获取结果,但它没有给我g,h值

xpath.compile("//a/b/*[self::c or self::d or self::f/text()");
Run Code Online (Sandbox Code Playgroud)

我使用的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()); 
   }
}
Run Code Online (Sandbox Code Playgroud)

}

谁能帮我这个?

非常感谢!!!

Pet*_*nov 7

如果要选择所有c,d,g,h节点,请使用此xpath:

"//c|//d|//g|//h"
Run Code Online (Sandbox Code Playgroud)

如果要从根指定完整路径,请使用此选项:

"/a/b/c|/a/b/d|/a/b/f/g|/a/b/f/h"
Run Code Online (Sandbox Code Playgroud)

或者如果你想要所有c,d,g或h,它们都在b中:

"//b//c|//b//d|//b//g|//b//h"
Run Code Online (Sandbox Code Playgroud)

此外,在您的代码中:使用nodes.item(i).getTextContent()而不是GetNodeValue.