DOM4J parses XML

Source: Internet
Author: User

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

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.