DEMO
1 List booklist = new ArrayList (); 2 String id = ""; 3 String title = ""; 4 String price = ""; 5 // Obtain the instance factory 6 DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); 7 // get resolution 8 DocumentBuilder builder = factory. newDocumentBuilder (); 9 // Obtain document10 11 Document document = builder. parse ("books. xml "); // errors in the root directory books. xml12 13 14 // Get All book nodes 15 NodeList element = document. getElementsByTagName ("book"); 16 // traverse the book node 17 for (int I = 0; I <element. getLength (); I ++) {18 // get each book Node 19 node Node = element. item (I); 20 // The node is converted to Element 21 Element bookElement = (Element) node; 22 id = bookElement. getAttribute ("id"); 23 // get all child nodes 24 NodeList childNodeList = bookElement. getChildNodes (); 25 // traverse node 26 for (int c = 0; c <childNodeList. getLength (); c ++) {27 Node cNode = childNodeList. item (c); 28 // Get the node name 29 30 String cName = cNode. getNodeName (); 31 32 // whether it is title33 if ("title ". equals (cName) 34 {35 title = cNode. getTextContent (); 36 37} 38 if ("price ". equals (cName) 39 {40 price = (Element) cNode ). getAttribute ("unit"); 41 price + = cNode. getTextContent (); 42} 43 44 45} 46 47 48 book bo = new book (); 49 bo. setId (id); 50 bo. setName (title); 51 bo. setPrice (price); 52 53 booklist. add (bo); // add to list
XML file
1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <books> 3 <book id = "b001"> 4 <title> Java Core </title> 5 <price> 34 </price> 6 </book> 7 <book id = "b002"> 8 <title> Thinking in Java </title> 9 <price unit = "¥"> 98 </price> 10 </book> 11 </books>
DOM parsing XML