Android parsing XML Summary-three methods: SAX, Pull, and Dom
Xml File Parsing is often used in android development. common xml parsing methods include SAX, Pull, and Dom. Recently I made a CSDN reader for android, using two of them (sax and pull). Today I will summarize these three methods for parsing xml in android.
The xml example (channels. xml) is as follows:
I. Using the sax Method for parsing
Basic knowledge:
This parsing method is an event-driven api, which has two parts: the parser and the event processor. The parser is the XMLReader interface, which reads XML documents, and send events (also the event source) to the event processor. The event processor ContentHandler interface is responsible for processing the event responses and XML documents.
The following are common ContentHandler interfaces.
Public abstract void characters (char [] ch, int start, int length)
This method is used to receive character block notifications. The parser uses this method to report character data blocks. To improve the resolution efficiency, the parser puts all the strings read into a character array (ch, in the method passed as a parameter to character, if you want to obtain the character data read in this event, you need to use the start and length attributes.
Public abstract void startDocument () receives the notification of the beginning of the document
Public abstract void endDocument () receives the end notification of the document
Public abstract void startElement (String uri, String localName, String qName, Attributes atts) receives the start tag of the document
Public abstract void endElement (String uri, String localName, String qName) receives the end tag of the document
To simplify development, the org. xml. sax. helpers provides a DefaultHandler class, which implements
ContentHandler method, we just want to inherit the DefaultHandler method.
In addition, the SAX parser provides a factory class: SAXParserFactory. The SAX parsing class is SAXParser which can call its parser Method for parsing.
1 public class SAXPraserHelper extends DefaultHandler {
2
3 final int ITEM = 0x0005;
4
5 List List;
6 channel chann;
7 int currentState = 0;
8
9 public List GetList (){
10 return list;
11}
12
13 /*
14 * interface character block notification
15 */
16 @ Override
17 public void characters (char [] ch, int start, int length)
18 throws SAXException {
19 // TODO Auto-generated method stub
20 // super. characters (ch, start, length );
21 String theString = String. valueOf (ch, start, length );
22 if (currentState! = 0 ){
23 chann. setName (theString );
24 currentState = 0;
25}
26 return;
27}
28
29 /*
30 * Receiving document end notification
31 */
32 @ Override
33 public void endDocument () throws SAXException {
34 // TODO Auto-generated method stub
35 super. endDocument ();
36}
37
38 /*
39 * receive tag end notification
40 */
41 @ Override
42 public void endElement (String uri, String localName, String qName)
43 throws SAXException {
44 // TODO Auto-generated method stub
45 if (localName. equals (item ))
46 list. add (chann );
47}
48
49 /*
50 * Document start notification
51 */
52 @ Override
53 public void startDocument () throws SAXException {
54 // TODO Auto-generated method stub
55 list = new ArrayList ();
56}
57
58 /*
59 * tag start notification
60 */
61 @ Override
62 public void startElement (String uri, String localName, String qName,
63 Attributes attributes) throws SAXException {
64 // TODO Auto-generated method stub
65 chann = new channel ();
66 if (localName. equals (item )){
67 for (int I = 0; I <attributes. getLength (); I ++ ){
68 if (attributes. getLocalName (I). equals (id )){
69 chann. setId (attributes. getValue (I ));
70} else if (attributes. getLocalName (I). equals (url )){
71 chann. setUrl (attributes. getValue (I ));
72}
73}
74 currentState = ITEM;
75 return;
76}
77 currentState = 0;
78 return;
79}
80}
1 private List GetChannelList () throws ParserConfigurationException, SAXException, IOException
2 {
3 // instantiate a SAXParserFactory object
4 SAXParserFactory factory = SAXParserFactory. newInstance ();
5 SAXParser parser;
6 // instantiate the SAXParser object, create the XMLReader object and parser
7 parser = factory. newSAXParser ();
8 XMLReader xmlReader = parser. getXMLReader ();
9 // instantiate handler, event Processor
10 SAXPraserHelper helperHandler = new SAXPraserHelper ();
11 // parser registration event
12 xmlReader. setContentHandler (helperHandler );
13 // read the file stream
14 InputStream stream = getResources (). openRawResource (R. raw. channels );
15 InputSource is = new InputSource (stream );
16 // parse the file
17 xmlReader. parse (is );
18 return helperHandler. getList ();
19}
From the second part of the code, we can see the steps for parsing XML using SAX:
1. instantiate a factory SAXParserFactory
2. instantiate the SAXPraser object and create the XMLReader parser.
3. instantiate handler and processor
4. register an event with the parser
5. Reading file streams
6. parsing files
Ii. pull Parsing
Basic knowledge:
In the android system, many resource files are in xml format. In the android system, the xml is parsed using the pul parser, it is the same as sax parsing (I personally think it is simpler than sax) and uses event-driven parsing. When the pull parser starts parsing, we can call its next () method to obtain the next parsing event (that is, the start document, end document, start tag, and end tag). When an element is in, you can call the getAttributte () of XmlPullParser () you can also use its nextText () method to obtain the value of this node.
1 private List > GetData (){
2 List > List = new ArrayList > ();
3 XmlResourceParser xrp = getResources (). getXml (R. xml. channels );
4
5 try {
6 // until the end of the document
7 while (xrp. getEventType ()! = XmlResourceParser. END_DOCUMENT ){
8 // if you encounter a start label
9 if (xrp. getEventType () = XmlResourceParser. START_TAG ){
10 String tagName = xrp. getName (); // obtain the Tag Name
11 if (tagName. equals (item )){
12 Map Map = new HashMap ();
13 String id = xrp. getAttributeValue (null, id); // obtain the attribute value through the attribute name
14 map. put (id, id );
15 String url = xrp. getAttributeValue (1); // obtain the attribute value through the Attribute Index
16 map. put (url, url );
17 map. put (name, xrp. nextText ());
18 list. add (map );
19}
20}
21 xrp. next (); // obtain the next event for parsing
22}
23} catch (XmlPullParserException e ){
24 // TODO Auto-generated catch block
25 e. printStackTrace ();
26} catch (IOException e ){
27 // TODO Auto-generated catch block
28 e. printStackTrace ();
29}
30
31 return list;
32}
Iii. Dom Parsing
Finally, let's take a look at the Dom parsing method. This method has never been used before for parsing (which is common in j2ee development and has not been used in this field). In the Dom parsing process, first, read all the dom files into the memory, and then use the dom api to traverse all the data and retrieve the desired data. This method is obviously a memory-consuming method, for mobile devices like mobile phones, memory is very limited, so this method is not recommended for large XML files, but Dom also has its advantages, it is more intuitive and simpler than the SAX method in some aspects. You can also use the dom method when the xml document is small.
The core code for Dom Parsing is as follows:
1 public static List GetChannelList (InputStream stream ){
3 List List = new ArrayList ();
4
5 // obtain the DocumentBuilderFactory object, which can obtain the DocumentBuilder object
6 DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance ();
7
8 try {
9 // obtain the DocumentBuilder object
10 DocumentBuilder builder = factory. newDocumentBuilder ();
11 // get the Document object representing the entire xml
12 Document document = builder. parse (stream );
13 // get the root node
14 Element root = document. getDocumentElement ();
15 // obtain all items nodes of the Root Node
16 NodeList items = root. getElementsByTagName (item );
17 // traverse all nodes
18 for (int I = 0; I 19 {
20 channel chann = new channel ();
21 Element item = (Element) items. item (I );
22 chann. setId (item. getAttribute (id ));
23 chann. setUrl (item. getAttribute (url ));
24 chann. setName (item. getFirstChild (). getNodeValue ());
25 list. add (chann );
26}
27
28} catch (ParserConfigurationException e ){
29 // TODO Auto-generated catch block
30 e. printStackTrace ();
31} catch (SAXException e ){
32 // TODO Auto-generated catch block
33 e. printStackTrace ();
34} catch (IOException e ){
35 // TODO Auto-generated catch block
36 e. printStackTrace ();
37}
38
39 return list;
40}
Summarize the Dom parsing steps (similar to sax)
1. Call the DocumentBuilderFactory. newInstance () method to obtain the DOM parser factory class instance.
2. Call the newDocumentBuilder () method of the parser factory instance class to obtain the DOM parser object.
3. Call the parse () method of the DOM parser object to parse the XML Document and obtain the Document object representing the entire Document.
Iv. Summary
In addition to the above three methods, there are many xml parsing methods, such as DOM4J and JDOM. However, there are two basic parsing Methods: one is event-driven (represented by SAX), and the other is based on the document structure (represented by DOM ). Others are just different syntaxes.
Http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/17/3082949.html
Http://blog.csdn.net/jueblog/article/details/13164349
Http://android.yaohuiji.com/archives/935