Search code examples
javaxml-parsingdom4j

Extracting child nodes data from given node


I want to use DOM4j for parsing xml file in Java.

I have this XML as an example:

<request method="POST" url="/devices/test/planner" body="*">
  <response statusCode="200">
    <header>
      <headerParameters>
        <headerParameter name="Content-Type">
          Content-Type=application/xml
        </headerParameter>
      </headerParameters>
    </header>
    <body>booking created!</body>
  </response>
</request>

Given the request (first node) node, how can I extract the child nodes data?

For example getting the <response> status code, or the <headerParameter> name attributes?


Solution

  • Assuming you get the "request" node as an Element then you can do something like this:

    Element response = (Element) request.elements().get(0);
    int statusCode = Integer.parseInt(response.attribute("statusCode"));
    

    If you want to traverse the children recursively then you'll have to write iterative (or recursive) code to visit each element in the list returned by the elements() method.

    [Edit] You can also use XPath to extract the specific items you're looking for:

    int statusCode = Integer.parseInt(
        request.selectSingleNode("response/@statusCode").getText());
    String firstHeaderName =
        request.selectSingleNode(
            "response/headerParameters/headerParameter/@name").getText();