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?
Assuming you get the "request" node as an
Element
then you can do something like this: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:
Extracting child nodes data from given node with dom4j:
1. Put this java code in a file called Main.java:
2. Put this in a file called /tmp/myxml.xml:
2. Put these jar files in a directory called lib in the same directory as Main.java:
3. Compile the program and run it from the terminal:
4. Interpret the output:
5. What just happened?
This uses Java version 1.7.0 and imports the dom4j version 1.6.1 library as well as a jaxen 1.1.1 support library. It imports the xml document, created by the user. Then it parses it with the SAXReader into a Document type. It uses the selectNodes(string) method to grab the PieHole xml tag. For every single PieHole xml tag, it will grab the cupcake and montana tags and place them into the Foo class. At the end, it prints what was inside Foo.