The sample code of Xml data parsing is described in detail.

Source: Internet
Author: User
Xml, as a data interaction format, involves the generation and resolution of xml data. three methods of Xml parsing are described here. I. Overview

Xml, as a data interaction format, involves the generation and resolution of xml data. three methods of Xml parsing are described here.

II. Dom parsing

1. create a parser factory object (DocumentBuilderFactory object)

2. create a parser object (DocumentBuilder)

3. create a Document object

For example, parsing the following files

 
         
               
   
    
1
                
   
    
Yang Wei
   Dalian21        
          
               
   
    
2
                
   
    
Ocean region
   Shenzhen23        
          
               
   
    
3
                
   
    
Wang Xiaobo
   Danzhou22        
  
 

The parsing code is as follows:

[Code] package com. kuxiao. train. xml; import java. io. file; import javax. xml. parsers. documentBuilder; import javax. xml. parsers. documentBuilderFactory; import org. w3c. dom. document; import org. w3c. dom. element; import org. w3c. dom. nodeList; public class XmlParseTest {public static void main (String [] args) throws Exception {// xml doc parsing step // 1. obtain the resolution factory object DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance (); // 2. build the parser object DocumentBuilder db = dbf. newDocumentBuilder (); // 3. construct the docment object Document doc = db. parse (new File ("person. xml "); Element ele = doc. getDocumentElement (); // implements the parsing logic NodeList list = doc. getElementsByTagName ("student"); for (int I = 0; I <list. getLength (); I ++) {Element element = (Element) list. item (I); String attrid = element. getAttribute ("id"); System. out. println ("attrid =" + attrid); Element element1 = (Element) element. getElementsByTagName ("id "). item (0); String id = element1.getFirstChild (). getNodeValue (); System. out. println (id); element1 = (Element) element. getElementsByTagName ("name "). item (0); String name = element1.getFirstChild (). getNodeValue (); System. out. println (name); element1 = (Element) element. getElementsByTagName ("address "). item (0); String address = element1.getFirstChild (). getNodeValue (); System. out. println (address );}}}

III. Notes

1. Element ele = doc. getDocumentElement (); get the root Element

2. when an element is obtained, the element value is also a node and must be the value of the element. getFirstChild (). getNodeValue () method.

3. the blank space in xml is also of the Node and text type.

IV. SAX parsing

1. create a SAXParserFactory object

2. create a SAXparser object

3. create MyHandler to inherit the DefaultHandler class and override the method.

4. sp. parse (new File ("student. xml"), new MyHandler (list ));

[Code] package com. kuxiao. train. xml. sax; import java. io. file; import java. util. arrayList; import java. util. list; import java. util. stack; import javax. xml. parsers. SAXParser; import javax. xml. parsers. SAXParserFactory; import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler; public class TestSax {public static void main (String [] args) throws Exception {SAXParserFactory spf = SAXParserFactory. newInstance (); SAXParser sp = spf. newSAXParser (); List
 
  
List = new ArrayList <> (); sp. parse (new File ("student. xml "), new MyHandler (list); System. out. println (list) ;}} class MyHandler extends DefaultHandler {private Stack
  
   
Stack = new Stack <> (); private Student student; private List
   
    
MList = null; public MyHandler (List
    
     
List) {this. mList = list;} @ Override public void startDocument () throws SAXException {System. out. println ("the parsing document has started... ") ;}@ Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {if (qName. equals ("student") {Student = new student (); if (attributes. getLength ()! = 0) {for (int I = 0; I <attributes. getLength (); I ++) {String id = attributes. getValue (I); student. setId (Integer. parseInt (id) ;}}/ * if (qName. equals ("name") {stack. push (qName);} if (qName. equals ("age") {stack. push (qName);} if (qName. equals ("gender") {stack. push (qName);} */stack. push (qName) ;}@ Override public void characters (char [] ch, int start, int length) throws SAXException {String qName = stack. peek (); if (qName. equals ("gender") {student. setGender (new String (ch, start, length);} if (qName. equals ("name") {student. setName (new String (ch, start, length);} if (qName. equals ("age") {student. setAge (new String (ch, start, length) ;}@ Override public void endElement (String uri, String localName, String qName) throws SAXException {stack. pop (); if (qName. equals ("student") {mList. add (student); student = null ;}@ Override public void endDocument () throws SAXException {System. out. println ("the parsing document is over ..... ");}}
    
   
  
 

SAX is based on the event model and performs sequential parsing. the internal implementation is the observer mode, which has the advantage of low memory usage and high efficiency. The disadvantage is that the encoding is relatively complicated.

5. Pull parsing

1. this resolution method is not provided by JDK and needs to be imported to a third-party library.

2. create an XmlPullParserFactory object

3. create an XmlPullParser object

4. call xpp. setInput (is, "UTF-8 ")

5. corresponding event type processing xpp. next () next event type

[Code] package com. kuxiao. train. xml. pull; import java. io. file; import java. io. fileInputStream; import java. io. inputStream; import java. lang. reflect. method; import java. util. arrayList; import java. util. list; import org. xmlpull. v1.XmlPullParser; import org. xmlpull. v1.XmlPullParserFactory; public class PullTest {public static void main (String [] args) throws Exception {FileInputStream is = new FileInputStream (new File ("person. xml "); long time = System. currentTimeMillis (); List
 
  
List = new ArrayList <> (); XmlPullParserFactory xppf = XmlPullParserFactory. newInstance (); XmlPullParser xpp = xppf. newPullParser (); xpp. setInput (is, "UTF-8"); Student student = null; int eventType = xpp. getEventType (); while (eventType! = XmlPullParser. END_DOCUMENT) {switch (eventType) {case XmlPullParser. START_TAG: if (xpp. getName (). equals ("student") {student = new Student (); String id = xpp. getAttributeValue (0); student. setId (id);} else if (xpp. getName (). equals ("name") {student. setName (xpp. nextText ();} else if (xpp. getName (). equals ("address") {student. setAddress (xpp. nextText ();} else if (xpp. getName (). equals ("age") {student. setAge (xpp. nextText ();} break; case XmlPullParser. START_DOCUMENT: System. out. println ("started .... "); break; case XmlPullParser. END_TAG: if (xpp. getName (). equals ("student") {list. add (student); student = null;} break;} eventType = xpp. next ();} is. close (); long time1 = System. currentTimeMillis (); System. out. println (time1-time); for (Student student2: list) {System. out. println (student2);} FileInputStream FD = new FileInputStream (new File ("person. xml "); List
  
   
List1 = getListBean (FS, new String [] {"id", "name", "address", "age", "gender"}, Student. class, 0); for (Student student2: list1) {System. out. println (student2 );}} // the encapsulated method for parsing xml files. // parameter description // attrs is the element and attribute name of the bean object in the file. // clazz is the class object of the Bean object. // j represents public static attribute count
   
    
List
    
     
GetListBean (InputStream is, String [] attrs, Class
     
      
Clazz, int j) throws Exception {long time = System. currentTimeMillis (); T c = null; XmlPullParserFactory xppf = XmlPullParserFactory. newInstance (); XmlPullParser xpp = xppf. newPullParser (); xpp. setInput (is, "UTF-8"); List
      
        List = null; int eventType = xpp. getEventType (); String classname = ""; while (eventType! = XmlPullParser. END_DOCUMENT) {switch (eventType) {case XmlPullParser. START_TAG: int bigen = clazz. getName (). lastIndexOf (". ") + 1; classname = clazz. getName (). substring (bigen); classname = classname. substring (0, 1 ). toLowerCase () + classname. substring (1); String elementName = xpp. getName (); if (classname. equals (elementName) {c = clazz. newInstance (); if (xpp. getAttributeCount ()! = 0) {for (int I = 0; I <j; I ++) {String attrName = xpp. getAttributeName (I); for (String field: attrs) {if (field. equals (attrName) {String frist = field. substring (0, 1 ). toUpperCase (); Method method = clazz. getDeclaredMethod ("set" + frist + field. substring (1), new Class [] {String. class}); method. setAccessible (true); method. invoke (c, xpp. getAttributeValue (I) ;}}}} else {for (String field: attrs) {if (field. equals (elementName) {String frist = field. substring (0, 1 ). toUpperCase (); Method method = clazz. getDeclaredMethod ("set" + frist + field. substring (1), new Class [] {String. class}); method. setAccessible (true); method. invoke (c, xpp. nextText () ;}}break; case XmlPullParser. START_DOCUMENT: list = new ArrayList
       
         (); Break; case XmlPullParser. END_TAG: if (! Classname. equals ("") & classname. equals (xpp. getName () {list. add (c); c = null;} break;} eventType = xpp. next ();} is. close (); long time1 = System. currentTimeMillis (); System. out. println (time1-time); return list ;}}
       
      
     
    
   
  
 

The above section details the sample code of the three methods of Xml data parsing. For more information, see other related articles in the first PHP community!

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.