Read xml
public class Dom4jDemo { public static void main(String[] args) throws Exception{ /* * Use Dom4j API to read XML file */ SAXReader reader=new SAXReader(); File File = new new File ( "the Books.xml" ); // use SAXReader read books.xml, if the reading is successful it will create a dom objects // The structure is tree. If the read fails or throws an exception: xml format, the file can not find the Document DOC = reader.Read (File); // result of the check reading // System.out.println (doc.asXML ()); // found root element, access entry as the element = the root doc.getRootElement (); // the root element is books // System.out.println (root.asXML ()); // goal: all title // 1. Get all the sub-elements the API List <the element> List =root.elements (); // for (the Element E: List) { // System.out.println (e.asXML ()); // } // 2. get all the specified name sub-element list = root.elements ( "book" ); for (the element E: List) { // E is a book element // book has three sub-elements DATE author name // System.out.println (e.asXML ()); // 3. find a first element of the sub-element matches the element n-e.element = ( "name" ); // System.out.println (n.asXML ()); // 4. Get the text elements String name = n.getTextTrim(); System.out.println(name); // E is a book element contains attributes // The element read attribute String ID = e.attributeValue ( "ID" ); System.out.println(id); } } }
public class Dom4jDemo2 { public static void main(String[] args) throws Exception { /* * Direct reading sub-element of the text * e.elementTextTrim("name"); */ File file=new File("books.xml"); SAXReader reader = new SAXReader(); Document doc=reader.read(file); Element root = doc.getRootElement (); List<Element> books=root.elements("book"); for(Element book:books) { String name= book.elementTextTrim("name"); System.out.println(name); } } }