If you have a simple xml file like the following one, I will show you how to use dom4j to find data.
<?xml version="1.0"?> <students> <student> <name>Mike</name> <course>JSP</course> </student> <student> <name>Janet</name> <course>EJB</course> </student> </students>
The file name is students.xml.
Suppose, you need to find the course for a student named Mike.
First, you need to parse a document:
public Document parse(String file) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(file); return document; } Document doc= parse("students.xml");
Then, use the following statement:
String course = doc.valueOf("//student[name='Mike']/course"); This statement uses an XPath Engine library from Jaxen which means you need to have it in your classpath. If you want to limit your library usage to dom4j proper you'll have to write your own method which may look like the following:
public String findStudentCourse(Document doc, String studentName) { Element root = doc.getRootElement(); for (Iterator i = root.elementIterator(); i.hasNext();) { Element el = (Element) i.next(); if (el.elementText("name").equals(studentName)) { return el.elementText("course"); } } return null; }If you want to iterate through all the student elements and print the name-course combinations use the following example:
Element root = document.getRootElement(); for (Iterator i = root.elementIterator(); i.hasNext();) { Element el = (Element) i.next(); System.out.println("Child Element Path :" + el.getPath()); System.out.println(" Name:" + el.elementText("name")); System.out.println(" Course:" + el.elementText("course")); }
No comments:
Post a Comment