java 使用 XPath 获取 XML 子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11755680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:15:30  来源:igfitidea点击:

Getting XML child elements with XPath

javaxmlxpath

提问by Michael A

I have this XML:

我有这个 XML:

<root>
  <items>
    <item1>
      <tag1>1</tag1>            
      <sub>
        <sub1>10 </sub1>
        <sub2>20 </sub2>
      </sub>
    </item1>

    <item2>
      <tag1>1</tag1>            
      <sub>
        <sub1> </sub1>
        <sub2> </sub2>
      </sub>        
    </item2>
  </items>
</root>

I want to get the item1element and the name and values of the child elements.

我想获取item1元素以及子元素的名称和值。

That is, i want to get: tag1- 1,sub1-10,sub2-20.

也就是说,我想得到:tag1- 1 ,sub1 -10 ,sub2 -20

How can i do this? so far i can only get elements without children.

我怎样才能做到这一点?到目前为止,我只能获得没有孩子的元素。

回答by Avihai Marchiano

Document doc = ...;
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/root/items/item1/*/text()");
Object o = expr.evaluate(doc, XPathConstants.NODESET);
NodeList list = (NodeList) o;

回答by Franco Rondini

import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
/**
* File: Ex1.java @author ronda
*/
public class Ex1 {
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = Factory.newDocumentBuilder();
    Document doc = builder.parse("myxml.xml");

    //creating an XPathFactory:
    XPathFactory factory = XPathFactory.newInstance();
    //using this factory to create an XPath object: 
    XPath xpath = factory.newXPath();

    // XPath Query for showing all nodes value
    XPathExpression expr = xpath.compile("//" + "item1" + "/*");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    System.out.println(nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {

        Element el = (Element) nodes.item(i);

        System.out.println("tag: " + el.getNodeName());
        // seach for the Text children
        if (el.getFirstChild().getNodeType() == Node.TEXT_NODE)
            System.out.println("inner value:" + el.getFirstChild().getNodeValue());

        NodeList children = el.getChildNodes();
        for (int k = 0; k < children.getLength(); k++) {
            Node child = children.item(k);
            if (child.getNodeType() != Node.TEXT_NODE) {
                System.out.println("child tag: " + child.getNodeName());
                if (child.getFirstChild().getNodeType() == Node.TEXT_NODE)
                    System.out.println("inner child value:" + child.getFirstChild().getNodeValue());;
            }
        }
    }
}
}

I get this output loading the xml of your question in file named: myxml.xml:

我得到这个输出,在名为 myxml.xml 的文件中加载你的问题的 xml:

run:
2
tag: tag1
inner value:1
tag: sub
inner value:

child tag: sub1
inner child value:10 
child tag: sub2
inner child value:20

...a bit wordy, but allow us to understand how it works. PS: I found a good guide in here

...有点罗嗦,但让我们了解它是如何工作的。PS:我在这里找到了一个很好的指南