Java Parsing XML document

Source: Internet
Author: User

Java Parsing XML document

First, parse the XML document way:

1, Dom mode: The entire XML document is read into memory, according to the XML file tree structure diagram to parse.

2, Sax mode: Based on event parsing, only need to load part of the data in the XML, the advantage is that the use of less resources, memory consumption is small.

XML document:

  

<?XML version= "1.0" encoding= "UTF-8"?><Students><Student><Name> Zhang San</Name><Age>20</Age></Student><Student><Name> John Doe</Name><Age>22</Age></Student><Student><Name> Harry</Name><Age>24</Age></student> <student> <name > Zhao Liu </name> <age>21< Span style= "color: #0000ff;" ></age> </< Span style= "color: #800000;" >student></ Students>          

Second, Dom parsing mode:

Documentbuilderfactory DBF =Documentbuilderfactory.newinstance ();D Ocumentbuilder db =Dbf.newdocumentbuilder ();D ocument doc = db.parse ("Src/students.xml"); NodeList list = doc.getelementsbytagname ("Student"); For (int i = 0; i < list.getlength (); i++) {node node = List.item (i); NodeList stulist = node.getchildnodes (); For (int j = 0; J < Stulist.getlength (); j + +) {
An empty element #text is included by default in the XML and needs to be skipped if (Stulist.item (j). Getnodename (). Equals ("#text")) continue; Node Childnode = Stulist.item (j); System.out.println (Childnode.getnodename () + ":" + childnode.gettextcontent ());}}
Output Result:
Name: Zhang San age:20name: John Doe age:22name: Harry Age:24

Java Parsing XML document

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.