1. Create a lib folder under the Project root directory
2. Copy the dom4j file to the lib folder.
3. dom4j, right-click Build Path ----> Add To Build Path
In this way, dom4j is successfully added to the project.
/**
* 1. Get the parsing stream
* 2. xml file parsing
* 3. Get the root element
* 4. Obtain all elements and process them cyclically.
*/
1 // get resolution stream 2 SAXReader reader = new SAXReader (); 3 // parse xml file 4 Document document = reader. read ("books. xml "); 5 // Obtain the root Element 6 Element rootElement = document. getRootElement (); 7 // get all elements 8 List list = rootElement. elements (); 9 for (int I = 0; I <list. size (); I ++) {10 book bo = new book (); 11 // A book node 12 Element bookelement = (Element) list. get (I); 13 // get the attribute value 14 String id = bookelement. attributeValue ("id"); 15 16 bo. setId (id); 17 // the child element 18 List childList = bookelement in the book element. elements (); 19 for (int c = 0; c <childList. size (); c ++) {20 Element childElement = (Element) childList. get (c); 21 // get the text value 22 String content = childElement. getTextTrim (); 23 // judge whether it is title or price24 if ("title ". equals (childElement. getName () 25 {26 bo. setName (content); 27} 28 if ("price ". equals (childElement. getName () 29 {30 bo. setPrice (childElement. attributeValue ("unit") + content); 31 System. out. println (childElement. attributeValue ("unit") + content); 32} 33 34} 35 booklist. add (bo); 36}
DOM4J parses XML