java - xpath多标签选择

标签 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>

我想过使用 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/

相关文章:

java - JTabbedPane Swing 更新错误

xpath - 如何在不具有名称的sql查询中获取xmlelement的子级?

selenium - 在xpath中定位self或perent节点的同级元素

java - 如何禁止访问依赖项的依赖项

Java 256 位 AES 基于密码的加密

java - 是否有一个通用的数据结构来表示 Java 中的列表映射

xml - 为给定的 XML 模式生成 Stax Writer API

c# - 使用 XmlSerializer 解析 xml 时出错

java - 使用 XML 生成 JAXB 类

javascript - XSL 模板导致加载速度非常慢