DOM parsing XML

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.