简体   繁体   中英

Java - read xml file

In Java I am using DocumentBuilderFactory, DocumentBuilder, and Document to read an xml file. But now I want to make a method that returns an arraylist of all values which follow a given node sequence. To explain better I'll give an example: Say I have the following xml file:

<one>
  <two>
    <three>5</three>
    <four>6</four>
  </two>
  <two>
    <three>7</three>
    <four>8</four>
  </two>
</one>

And I use the method with a string parameter "one.two.three", now the return value should be an array containing the numbers 5 and 7.

How can I build this arraylist?

you can use xpath, albeit the syntax is slightly different than dots (uses slash)

    Document d = ....

    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/one/two/three/text()"); // your example expression
    NodeList nl = (NodeList) expr.evaluate(d, XPathConstants.NODESET);
    for (int i = 0; i < nl.getLength(); i++) {
        String n = nl.item(i).getTextContent();
        System.out.println(n); //now do something with the text, like add them to a list or process them directly
    }

you can find more on how to query nodes using xpath here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM