1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply! I'll test it out in a bit since I have to leave home soon. I'll post it here if it worked in a few hours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.