Summary of how Java reads XML files

Source: Internet
Author: User

http://blog.csdn.net/ahangliu/article/details/1533127

Test1.xml File Contents

<?xml version= "1.0" encoding= "GB2312"?>  <RESULT>  <VALUE>     <no>a1234</no  >     <ADDR> henan Zhengzhou </ADDR>  </VALUE>  <VALUE>     <NO>B1234</NO>     <ADDR> Zhengzhou City, Henan province, Erqi District </ADDR>  </VALUE>  </RESULT>   
the first method of DOM implementation: DOM is based on the parsing of XML document tree structure
DOM is the official standard for representing XML documents in a platform-and language-neutral way. The DOM is a collection of nodes or pieces of information that are organized in a hierarchical structure. This hierarchy allows developers to look for specific information in the tree. Analyzing the structure usually requires loading the entire document and constructing the hierarchy before any work can be done. Because it is based on the information hierarchy, the DOM is considered to be tree-based or object-based. Dom and the generalized tree-based processing have several advantages. First, because the tree is persistent in memory, you can modify it so that the application can make changes to the data and structure. It can also navigate up and down the tree at any time, rather than a one-off process like sax. Dom is much simpler to use.

<pre name= "code" class= "java" >import java.io.file;import Javax.xml.parsers.documentbuilder;import Javax.xml.parsers.documentbuilderfactory;import Org.w3c.dom.document;import Org.w3c.dom.nodelist;public Class myxmlreader2dom {public static void main (String arge[]) {Long lasting = System.currenttimemillis (); try {file F = new File ( "Data_10k.xml");D ocumentbuilderfactory factory = documentbuilderfactory.newinstance ();D Ocumentbuilder builder = Factory.newdocumentbuilder ();D ocument doc = Builder.parse (f); NodeList nl = doc.getelementsbytagname ("VALUE"); for (int i = 0; i < nl.getlength (); i++) {System.out.print ("license plate number:" + doc . getElementsByTagName ("NO"). Item (i). Getfirstchild (). Getnodevalue ()); System.out.println ("Owner's address:" + doc.getelementsbytagname ("ADDR"). Item (i). Getfirstchild (). Getnodevalue ());}} catch (Exception e) {e.printstacktrace ();}}}

The second method dom4j

Dom4j is a very, very good Java XML API that features excellent performance, power, and extreme ease of use, and is also an open source software. Now you can see that more and more Java software is using dom4j to read and write XML, especially to mention that even Sun's JAXM is using DOM4J.

public class Myxmlreader2dom4j {public   static void Main (String arge[]) {     long lasting = System.currenttimemillis ();     try {       file F = new File ("Data_10k.xml");       Saxreader reader = new Saxreader ();       Document doc = Reader.read (f);       Element root = Doc.getrootelement ();       Element foo;       for (Iterator i = root.elementiterator ("VALUE"); I.hasnext ();) {        foo = (Element) i.next ();        System.out.print ("License plate number:" + foo.elementtext ("NO"));        System.out.println ("Owner's address:" + foo.elementtext ("ADDR"));}      } catch (Exception e) {       e.printstacktrace ();}}   }  

The third method of jdom implementation

In order to reduce the number of DOM, sax encoding, there is a jdom; Pros: 20-80 principle, greatly reducing the amount of code. Use occasions: to achieve simple functions, such as parsing, creation, etc., but at the bottom, Jdom still use sax (most commonly used), DOM, Xanan documents.


Import java.io.*;   Import java.util.*;   Import org.jdom.*;   Import org.jdom.input.*;     public class Myxmlreader2jdom {public   static void Main (String arge[]) {     Long lasting = System.currenttimemillis ( );     try {       Saxbuilder builder = new Saxbuilder ();       Document doc = builder.build (new File ("Data_10k.xml"));       Element foo = doc.getrootelement ();       List Allchildren = Foo.getchildren ();      for (int i = 0; i < allchildren.size (); i++) {        System.out.print ("License plate Number:" + (Element) allchildren.get (i)). Getchild ( "NO"). GetText ());        System.out.println ("Owner's Address:" + (Element) allchildren.get (i)). Getchild ("ADDR"). GetText ());       }      } catch (Exception e) {       e.printstacktrace ();}}   }  

Fourth method of SAX implementation

Sax has emerged to solve the DOM problem. SAX, event-driven. When the parser discovers the start of an element, the end of an element, text, the beginning or end of a document, and so on, the programmer writes the code that responds to these events and saves the data. Pros: No need to transfer the entire document in advance, consume less resources, SAX parser code is smaller than DOM parser code, suitable for applets, download. Cons: not persistent; After the event, if the data is not saved, then the data is lost, stateless, only the text can be obtained from the event, but the text is not known which element; use case: Applet; only a small amount of XML documents, little back access, less machine memory;

Import Javax.xml.parsers.SAXParser;     Import Javax.xml.parsers.SAXParserFactory;   Import org.xml.sax.Attributes;   Import Org.xml.sax.InputSource;   Import org.xml.sax.SAXException;     Import Org.xml.sax.helpers.DefaultHandler;     public class Myxmlreader2sax extends DefaultHandler {java.util.Stack tags = new java.util.Stack ();   Public Myxmlreader2sax () {super ();     } public static void Main (String args[]) {Long lasting = System.currenttimemillis ();       try {saxparserfactory SF = saxparserfactory.newinstance ();       SAXParser sp = Sf.newsaxparser ();       Myxmlreader2sax reader = new Myxmlreader2sax ();      Sp.parse (New InputSource ("Data_10k.xml"), reader);      } catch (Exception e) {e.printstacktrace ();   } System.out.println ("Run Time:" + (System.currenttimemillis ()-lasting) + "MS"); } public void characters (char ch[], int start, int length) throws Saxexception {string tag = (string) tags.     Peek (); if (tag.eqUals ("NO")) {System.out.print ("license plate number:" + New String (CH, start, length));      } if (Tag.equals ("ADDR")) {System.out.println ("Address:" + New String (CH, start, length)); }} public void Startelement (string uri, String localname, String qName, Attributes attrs) {Tags.push (QN     AME);   }   }

Summary of how Java reads XML files

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.