从特定树级获取XML节点

Mat*_*att 4 java xml xpath

我需要一个像Document.getElementsByTagName()这样的方法,但是只搜索某个级别的标签(即不是具有相同名称的嵌套标签)

示例文件:

<script>
  <something>
    <findme></findme><!-- DO NOT FIND THIS TAG -->
  </something>
  <findme></findme><!-- FIND THIS TAG -->
</script>
Run Code Online (Sandbox Code Playgroud)

Document.getElementsByTagName()只返回文档中的所有findme标记.

Ala*_*ier 5

这是XPath的一个例子

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class TestXPath {

    private static final String FILE = "a.xml" ;
    private static final String XPATH = "/script/findme";
    public static void main(String[] args) {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        DocumentBuilder builder;
        try {
            builder = docFactory.newDocumentBuilder();
            Document doc = builder.parse(FILE);
            XPathExpression expr = XPathFactory.newInstance().newXPath().compile(XPATH);
            Object hits = expr.evaluate(doc, XPathConstants.NODESET ) ;
            if ( hits instanceof NodeList ) {
                NodeList list = (NodeList) hits ;
                for (int i = 0; i < list.getLength(); i++ ) {
                    System.out.println( list.item(i).getTextContent() );
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

<script>
  <something>
    <findme>1</findme><!-- DO NOT FIND THIS TAG -->
  </something>
  <findme>Find this</findme><!-- FIND THIS TAG -->
  <findme>More of this</findme><!-- FIND THIS TAG AS WELL -->
</script>
Run Code Online (Sandbox Code Playgroud)

它产生了

Find this
More of this
Run Code Online (Sandbox Code Playgroud)