[Android Notes] parsing xml files in Android

Source: Internet
Author: User

There are multiple ways to parse xml files in Android:Dom:

Highly versatile. It reads all the content of the XML file to the memory, and then allows you to use DOM APIs to traverse the XML tree and retrieve the required data, however, you need to read the document to the memory andNot suitable for mobile devices;

Sax:

 

SAX is an xml parser with high resolution speed and low memory usage. It is event-driven and does not need to parse the entire document. Implementation: inherits DefaultHandler, override methods such as startElement, endElement, and characters;

 

Pull:Android comes with an XML parser, which is similar to SAX and event-driven. The difference is that the PULL event returns a numeric type. We recommend that you use it. ------------------------------------------------------------------------ The following describes how to parse pull and sax. dom is generally not used on mobile devices, so skip it. -------------------------------------------------------------------------- I. pull parsing: 1. classes to be used:
android.util.Xmlorg.xmlpull.v1.XmlSerializerorg.xmlpull.v1.XmlPullParser

2. Whether Additional jar packages are required: No 3. Usage: 1. Create xml:A. Create an xmlSerializer object
 XmlSerializer serializer = Xml.newSerializer();
B. Set the output stream
 serializer.setOutput(outputstream,encoding)
C. Create an xml document and add nodes.
serializer.startDocument("utf-8",true);serializer.startTag(null,node_name);...serializer.endTag(null,node_name);serializer.endDocument();
2. parse xml:A. Create an xmlPullParser object
XmlPullParser parser = Xml.newPullParser();
B. Set the input stream
parser.setInput(inputstream,encoding);
C. Parsing
Int type = parser. getEventType (); while (type! = XmlPullParser. END_DOCUMENT) {switch (type) {case XmlPullParser. START_TAG: break; case XmlPullParser. END_TAG: break;} type = parser. next (); // do not forget this code}
4. Instance
/*** Use XmlSerializer to generate an xml file */private void makeXML () {List
 
  
Citys = Data. getCityData (); try {File path = Environment. getExternalStorageDirectory (); XmlSerializer serializer = Xml. newSerializer (); serializer. setOutput (new FileOutputStream (new File (path, "weather. xml ")," UTF-8 "); serializer. startDocument ("UTF-8", true); serializer. startTag (null, "info"); for (WeatherData city: citys) {serializer. startTag (null, "city"); serializer. attribute (null, "id", city. getId (); serializer. attribute (null, "name", city. getName (); serializer. startTag (null, "weather"); serializer. text (city. getWeather (); serializer. endTag (null, "weather"); serializer. startTag (null, "temp"); serializer. text (city. getTemp (); serializer. endTag (null, "temp"); serializer. startTag (null, "wind"); serializer. text (city. getWind (); serializer. endTag (null, "wind"); serializer. endTag (null, "city");} serializer. endTag (null, "info"); serializer. endDocument ();} catch (Exception e) {e. printStackTrace (); Toast. makeText (this, "failed to save", 0 ). show ();}}
 
Pull parses xml:
// Return List
 
  
> SimpleAdapter allows you to set the public static List of data sources.
  
   
> GetWeatherData (File file) {if (file = null) return null; XmlPullParser parser = Xml. newPullParser (); List
   
    
> List = null; Map
    
     
Map = null; try {parser. setInput (new FileInputStream (file), "UTF-8"); int type = parser. getEventType (); while (type! = XmlPullParser. END_DOCUMENT) {switch (type) {case XmlPullParser. START_TAG: if ("info". equals (parser. getName () {list = new ArrayList
     
      
> ();} Else if ("city". equals (parser. getName () {map = new HashMap
      
        (); Map. put ("city", parser. getAttributeValue (null, "name");} else if ("weather ". equals (parser. getName () {map. put ("weather", parser. nextText ();} else if ("temp ". equals (parser. getName () {map. put ("temp", parser. nextText ();} else if ("wind ". equals (parser. getName () {map. put ("wind", parser. nextText ();} break; case XmlPullParser. END_TAG: if ("city ". equals (parser. getName () {list. add (map); map = null;} break; default: break;} type = parser. next () ;}} catch (Exception e) {e. printStackTrace (); Log. I (TAG, e. getMessage ();} return list ;}
      
     
    
   
  
 
Xml file to be parsed (similarly, the weather Entity bean object is omitted ):
     
          
   
    
Clear
           
   
    
34
           
   
    
Dongfeng
       
      
          
   
    
Thundershower
           
   
    
24
           
   
    
Nanfeng
       
      
          
   
    
Sleet
           
   
    
32
           
   
    
West Wind
       
  
 
Ii. Analysis of sax 1. classes to be used:
A custom processor class that inherits org. xml. sax. helpers. DefaultHandler javax. xml. parsers. SAXParserFactory class javax. xml. parsers. SAXParser class, Parser
2 . Whether to expand the jar package: No 3. Usage:1. Define a processor based on the xml you want to parse (rewrite startDocument, startElement, characters, endElement method ):
 public class SaxHandler4Weather extends DefaultHandler{    @Override    public void startDocument() throws SAXException    {    }    @Override    public void startElement(String uri, String localName, String qName,            Attributes attributes) throws SAXException    {     }     @Override    public void endElement(String uri, String localName, String qName)            throws SAXException    {            }    @Override    public void characters(char[] ch, int start, int length)            throws SAXException    {    }}
2. Create a parser object using the parser factory
SAXParserFactory factory = SAXParserFactory.newInstance();        SAXParser parser = factory.newSAXParser();
3. parse xml using a custom Processor
parser.parse(file,handler);
4. A method similar to getData should be provided in the handler processor object to return the parsing result.
4. instance:1. Processor
Package cn.edu. chd. xmlutils; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler;/*** @ author Rowand jj ** parse the weather xml processor */public class SaxHandler4Weather extends DefaultHandler {private Map
 
  
Map = null; // stores the complete private List object of a single resolution
  
   
> List = null; // store all the parsing objects private String currentTag = null; // The tag private String currentValue = null for the element being parsed; // parse the current element value private String nodeName = "city"; // The xml file to be parsed represents the xml root node name of an object @ Override public void startDocument () throws SAXException {list = new ArrayList
   
    
> () ;}@ Override public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {if (qName. equals (nodeName) // discovers the city node {map = new HashMap
    
     
();} If (attributes! = Null & map! = Null) {for (int I = 0; I <attributes. getLength (); I ++) {if (attributes. getQName (I ). equals ("name") {map. put ("city", attributes. getValue (I) ;}}currenttag = qName ;}@ Override public void endElement (String uri, String localName, String qName) throws SAXException {if (qName. equals (nodeName) // a city node has been parsed {list. add (map); map = null ;}@ Override public void characters (char [] ch, int start, I Nt length) throws SAXException {if (currentTag! = Null & map! = Null) {currentValue = new String (ch, start, length ). trim (); if (nodeName. equals (currentTag) // city node {} else if ("weather ". equals (currentTag) // whether it is a weather node {map. put ("weather", currentValue);} else if ("temp ". equals (currentTag) // whether it is a temp node {map. put ("temp", currentValue);} else if ("wind ". equals (currentTag) // whether it is a wind node {map. put ("wind", currentValue) ;}} currentTag = null; currentValue = null;} public List
     
      
> GetList () {return list ;}}
     
    
   
  
 
2. parse xml:
public static List
 
  > getWeatherData(File file)    {        List
  
   > list = null;        try        {            SAXParserFactory factory = SAXParserFactory.newInstance();            SAXParser parser = factory.newSAXParser();            SaxHandler4Weather handler = new SaxHandler4Weather();            parser.parse(file,handler);            list = handler.getList();            Log.i(TAG,"-->size = "+list.size());        } catch (Exception e)        {            Log.i(TAG,e.getMessage());        }        return list;    }
  
 
------------------------------------------------ Download Sample Code



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.