XML is a clear and concise way to describe data.
Let’s see an example:
<?xml version="1.0" encoding="UTF-8"?>
<message id="123">
<from>Nikos</from>
<to>Sofia</to>
<text>Hello from XML!</text>
</message>
This simple document represents a “message”.
<message>
...
</message>
The message has an attribute called @id.
<message id="...">
...
</message>
It has also three children.
<from> ... </from> <to> ... </to> <text> ... </text>
Step 1. Download dom4j
To download dom4j go to dom4j.org → Download → Download the current release SourceForge → dom4j-1.6.1.jar
Note:
If you are using Java 1.5 download dom4j-1.5.2.jar, and
If you are using Java 1.4 download dom4j-1.4.zip; it has a dom4j-full.jar inside.
Step 2. Place the jar in the classpath
In Eclipse: Project → Java Build Path → Libraries → Add External JARs…
In Netbeans: File → ”Project” Properties → Libraries → Add JAR/Folder
In JDeveloper 11g: Tools → Project Properties… → Libraries and Classpath → Add JAR/Directory…
Step 3. Create the XML document
// Create the document Document document = DocumentHelper.createDocument(); // Add the root Element root = document.addElement("message").addAttribute("id", "123"); // Add the "from" element root.addElement("from").addText("Nikos"); // Add the "to" element root.addElement("to").addText("Sofia"); // Add the "text" element root.addElement("text").addText("Hello from XML!");
That’s all!
Step 4. Save the XML document
// Make a pretty output OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); format.setTrimText(false); // Save it XMLWriter writer = new XMLWriter(new FileWriter("C:/message.xml"), format); writer.write(document); writer.close();
Step 5. Read the XML document
// Locate the file URL url = new File("C:/message.xml").toURI().toURL(); // Parse the document Document document = new SAXReader().read(url);
Step 6. Get the information
// Get the root element Element root = document.getRootElement(); // Get the id attribute root.attributeValue("id"); // Get the from element Element from = root.element("from"); if (from != null) { from.getText(); }
Step 7. Use some XPATH
// Get the root element Element root = document.getRootElement(); // Get the id attribute root.valueOf("@id"); // Get the from element Node from = root.selectSingleNode("./from"); if (from != null) { from.getText(); }
A good XML tutorial can be found at w3schools.com.
Thank you.
21 May 2008 at 9:39 pm
Bravo Nikolae, this a good chance for all the junior developers to get familiars with programming.
Keep walking
We are with your side
2 December 2009 at 3:57 am
you may also want to check out vtd-xml, the latest and most advanced xml processing model
vtd-xml