[Android learning] Three parsing methods of XML text (providing XML files by setting up a local Web project)

Source: Internet
Author: User

XML is a scalable markup language. It is a simple data storage language that is described using a series of simple tags.

1. Analysis of SAX

That is, the Simple API for XML notifies the program in the form of events and parses the Xml.

1. First, release an XML document named persons. xml in the Web Project. The specific content is:

 
     
          
   
    
Jay Chou
   20    
      
          
   
    
James
   21    
  
 

2. The process for parsing the SAX file is as follows:

  

An instance is obtained by creating the SAXParserFactory object, and then a SaxParser is obtained through the factory. The parsing is completed by using the SaxParser parse method. The parse parameter is an InputStream class and a DefaultHandler class, defaultHandler needs to be rewritten

    SAXParserFactory spf = SAXParserFactory.newInstance();       SAXParser parse = spf.newSAXParser();       Myhandler handler = new Myhandler("person");       parse.parse(is, handler);       list = handler.getList();

  

3. Rewrite the processing class DefaultHandler.

  

  

Import java. util. arrayList; import java. util. hashMap; import java. util. list; import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler; public class Myhandler extends DefaultHandler {List
 
  
> List = null; // stores all the parsing objects String currentTag = null; // The tag String currentValue being parsed = null; // The value of the element being parsed String nodename = null; // parsing the node name HashMap
  
   
Map = null; // stores the complete public Myhandler (String nodename) {this. nodename = nodename;} public List of a single parsed object
   
    
> GetList () {return list;} @ Override // trigger public void startDocument () throws SAXException {list = new ArrayList when reading the first start tag
    
     
> () ;}@ Override // trigger public void startElement (String uri, String localName, String qName, Attributes attributes) when the node name to be parsed is encountered) throws SAXException {if (qName. equals (nodename) {map = new HashMap
     
      
();} If (attributes! = Null & map! = Null) {for (int I = 0; I <attributes. getLength (); I ++) {map. put (attributes. getQName (I), attributes. getValue (I) ;}}currenttag = qName ;}@ Override public void endElement (String uri, String localName, String qName) throws SAXException {if (qName. equals (nodename) {list. add (map); map = null;} super. endElement (uri, localName, qName) ;}@ Override // process the content read by the xml file public void characters (char [] Ch, int start, int length) throws SAXException {if (currentTag! = Null & map! = Null) {currentValue = new String (ch, start, length); if (currentValue! = Null &&! CurrentValue. trim (). equals ("")&&! CurrentValue. trim (). equals ("\ n") {map. put (currentTag, currentValue) ;}currenttag = null; currentValue = null ;}}
     
    
   
  
 

  

  

  

4. Get data from the server through the custom HttpUtils class and return the data in the form of a stream, that is, the input stream of the XML document. It is not provided here, three methods for obtaining server data will be updated next time.

 

5. Finally, use the returned List > After obtaining the content required by the XML document, we need to mention that I need to parse the person node here, so the parsing starts only when the qName is equal to the person node.

 

Ii. PULL Parsing

Similar to the SAX method, the program parses the Xml in the "pull" method.

1. Similar to SAX parsing, but easier than SAX parsing, the JAR package is required ,:

http://pan.baidu.com/s/1hq3JnKg

2. Create a factory through XMLPullFactory, and then create an XMLPullParser object for processing.

3. parse the eventType XML file node to obtain the data, and store the data in the List for return.

Import java. io. inputStream; import java. util. arrayList; import java. util. list; import org. xmlpull. v1.XmlPullParser; import org. xmlpull. v1.XmlPullParserException; import org. xmlpull. v1.XmlPullParserFactory; public class PullXmlHandler {public static List
 
  
ParseXml (InputStream is, String encode) throws Exception {List
  
   
List = null; Person p = null; try {XmlPullParserFactory xmlPullF = XmlPullParserFactory. newInstance (); XmlPullParser parser = xmlPullF. newPullParser (); parser. setInput (is, encode); int eventType = parser. getEventType ();
   // Keep repeating until the end node of the document is reachedWhile (eventType! = XmlPullParser. END_DOCUMENT) {switch (eventType) {case XmlPullParser. START_DOCUMENT: list = new ArrayList
   
    
(); Break; case XmlPullParser. START_TAG: if (parser. getName (). equals ("person") {p = new Person (); if (parser. getAttributeCount ()! = 0) {p. setId (parser. getAttributeValue (0);} else if (parser. getName (). equals ("name") {p. setName (parser. nextText ();} else if (parser. getName (). equals ("age") {p. setAge (parser. nextText ();} break; case XmlPullParser. END_TAG: if (parser. getName (). equals ("person") {list. add (p); p = null;} break; default: break ;}
    // Perform the next loopEventType = parser. next () ;}} catch (XmlPullParserException e) {// TODO Auto-generated catch block e. printStackTrace ();} return list ;}}
   
  
 
Iii. DOM Parsing

In the "Document Object Model" mode, the parsed Xml will generate a tree structure object.

1. DOM Parsing is more difficult than the first two methods. The Code is as follows:

  

Import java. io. inputStream; import java. util. arrayList; import java. util. list; import javax. xml. parsers. documentBuilder; import javax. xml. parsers. documentBuilderFactory; import org. w3c. dom. document; import org. w3c. dom. element; import org. w3c. dom. node; import org. w3c. dom. nodeList; import com. xml. httputils. http_post; public class DomService {public DomService () {} public static List
 
  
ParseXML (InputStream is) throws Exception {List
  
   
List = new ArrayList
   
    
(); DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); DocumentBuilder builder = factory. newDocumentBuilder (); Document document = builder. parse (is); // obtain the node Element = document. getDocumentElement (); NodeList nodeList = element. getElementsByTagName ("person"); for (int I = 0; I <nodeList. getLength (); I ++) {Element personElement = (Element) nodeList. item (I); Person p = new Person (); p. setId (personElement. getAttribute ("id"); NodeList personList = personElement. getChildNodes (); for (int j = 0; j <personList. getLength (); j ++) {if (personList. item (j ). getNodeType () = Node. ELEMENT_NODE) {if ("name ". equals (personList. item (j ). getNodeName () {p. setName (personList. item (j ). getFirstChild (). getNodeValue ();} else if ("age ". equals (personList. item (j ). getNodeName () {p. setAge (personList. item (j ). getFirstChild (). getNodeValue () ;}} list. add (p) ;}return list;} public static void main (String [] args) throws Exception {DomService dom = new DomService (); List
    
     
Ps = dom. parseXML (http_post.getXMLStream (); for (Person p: ps) {System. out. println (p );}}}
    
   
  
 

 

Summary:

For small memory devices, especially Android devices, PULL or SAX Parsing is far better than DOM parsing.

Related Article

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.