Retrieving child node data from a given node using dom4j:
1. Place this Java code in the Main.java file:
import java.util.*; import java.io.*; import org.dom4j.*; import org.dom4j.io.*; class Foo{ String moo; String baz; } class Main{ public static Document parse(String filePath) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(filePath); return document; } public static void main(String[] args){ try{ File f = new File("/tmp/myxml.xml"); Document document = parse(f.toString()); List list = document.selectNodes("//penguins/PieHole"); Foo foo = new Foo(); Iterator iter=list.iterator(); while(iter.hasNext()){ Element element=(Element)iter.next(); foo.moo = element.selectSingleNode("cupcake").getText(); foo.baz = element.selectSingleNode("montana").getText(); } System.out.println("foo.moo: " + foo.moo); System.out.println("foo.baz: " + foo.baz); } catch(Exception e){ e.printStackTrace(); } System.out.println("done"); } }
2. Put this in a file called /tmp/myxml.xml:
<?xml version="1.0" encoding="utf-8"?> <penguins> <mars>129</mars> <PieHole> <cupcake>value inside cupcake</cupcake> <montana>value inside montana</montana> </PieHole> </penguins>
2. Place these jar files in the lib directory in the same directory as Main.java:
dom4j-1.6.1.jar jaxen-1.1.1.jar
3. Compile the program and run it from the terminal:
javac -cp .:./lib/* Main.java java -cp .:./lib/* Main
4. To interpret the conclusion:
eric@defiant ~/code/java/run04 $ javac -cp .:./lib/* Main.java eric@defiant ~/code/java/run04 $ java -cp .:./lib/* Main foo.moo: value inside cupcake foo.baz: value inside montana done
5. What just happened?
It uses Java version 1.7.0 and imports the dom4j library version 1.6.1, as well as the jaxen 1.1.1 support library. It imports the user-created XML document. He then parses it using SAXReader into a document type. It uses the selectNodes (string) method to capture the PieHole xml tag. For each PieHole xml tag, it will grab the cupcake and montan tags and put them in the Foo class. In the end, he prints what was inside Foo.
Eric Leschinski
source share