Data storage (two)--sax Engine XML Memory (demo included)

Source: Internet
Author: User

The Android SDK supports the SAX read technology xml,sax to process XML files through sequential reads. This requires that each reading of the XML corresponds to an event triggered by the node that handles the node's file. The following is based on an example to tell sax to use:

public class Book {private string Name;private string Id;private string price;private string publisher;private int count;< c0/> .... Get,set method omitted}

XML files such as the following:

<?xml version= "1.0" encoding= "Utf-8"? ><books  xmlns:book= "http://schemas.android.com/ Com.example.jsonxmlio ">       <book         book:name=" Chinese "        book:id=" 001 "        book:price=" book       : Publisher= "A" >12</book>    <book         book:name= "math"        book:id= "002"        book:price= "       Book:publisher= "B" >10</book>    <book         book:name= "English"        book:id= "003"        book:price= "55 "       book:publisher=" C ">21</book> </books>


Xmltool.java

1. Build a factory SAXParserFactory
2. Build and instantiate Saxpraser objects

public class Xmltool {private static SAXParser Getsaxparser () throws Parserconfigurationexception, saxexception{        SAXParserFactory parserfactory = Saxparserfactory.newinstance ();        return Parserfactory.newsaxparser ();} public static DefaultHandler Parse (InputStream Instream,defaulthandler handler) {if (instream!=null) {try {SAXParser Parser = Getsaxparser ();p arser.parse (instream, handler); return handler;} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Finally{if (instream!=null) {try {instream.close ()} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} return null;}}

Bookxmlparser.java

public class Bookxmlparser extends Defaulthandler{private arraylist<book> datalist;private book Book;private StringBuffer StringBuffer = new StringBuffer ()//private stringbuffer buffer=new stringbuffer ();p ublic ArrayList< Book> GetData () {return dataList;} public void Startdocument () throws Saxexception {//TODO auto-generated Method stubdatalist = new arraylist<book> (); }public void Startelement (String uri, String localname, String Qname,attributes Attributes) throws Saxexception {//TODO A Uto-generated Method Stubif (Qname.equals ("book")} {book = new book (); Book.setname (Attributes.getvalue ("Book:name")); Book.setid (Attributes.getvalue ("Book:id")); Book.setprice (Attributes.getvalue ("Book:price")); Book.setPublisher ( Attributes.getvalue ("Book:publisher"));} Super.startelement (URI, LocalName, qName, attributes);} @Overridepublic void characters (char[] ch, int start, int length) throws Saxexception {//TODO auto-generated method Stubst Ringbuffer.append (ch,start,length); Super.characTers (CH, start, length);} @Overridepublic void EndElement (String uri, String localname, String qName) throws Saxexception {//TODO auto-generated met Hod stubif (Qname.equals ("book")) {if (stringbuffer.tostring ()!=null &&!stringbuffer.tostring (). Equals ("")) {Book.setcount (Integer.parseint () (Stringbuffer.tostring ())); Stringbuffer.setlength (0);//Must empty buffer} Datalist.add (book);} Super.endelement (URI, LocalName, QName);}}

The SAX engine needs to handle 5 analysis points, which can also be called analysis events.

1. Start parsing the XML file.

This analysis point indicates that the SAX engine has just started processing an XML file. However, the content in the XML file has not been read, and the analysis point corresponds to:

public void Startdocument () throws Saxexception {//TODO auto-generated Method stubdatalist = new arraylist<book> (); }

In this method, you can do some initialization work.

2. Start processing each XML element.

That is, when encountering <book> this starting tag will trigger the analysis node, the corresponding event method is startelement. This node is able to obtain information about the name and attributes of the element.

public void Startelement (string uri, String localname, String Qname,attributes Attributes) throws Saxexception {//TODO Au To-generated Method Stubif (Qname.equals ("book")} {book = new book (); Book.setname (Attributes.getvalue ("Book:name")); Book.setid (Attributes.getvalue ("Book:id")); Book.setprice (Attributes.getvalue ("Book:price")); Book.setPublisher ( Attributes.getvalue ("Book:publisher"));} Super.startelement (URI, LocalName, qName, attributes);}

3. Finish processing each XML element.

The EndElement method is triggered when the end tag is encountered </book>. In this event, you can get all the information that is currently finished with the element.

public void EndElement (string uri, String localname, String qName) throws Saxexception {//TODO auto-generated method Stubi F (Qname.equals ("book")) {if (stringbuffer.tostring ()!=null &&!stringbuffer.tostring (). Equals ("")) { Book.setcount (Integer.parseint (stringbuffer.tostring (). Trim ())) stringbuffer.setlength (0);//Must empty buffer} Datalist.add (book);} Super.endelement (URI, LocalName, qName);}

4. Finish processing the XML file. Assume that the SAX engine will start the Enddocument method by scanning through all the XML files. This approach may not be necessary, but there are some finishing touches to be done in this approach. Let's say release resources. I'm not using it in this case.

5. Read the character analysis point.

This is a very important point of analysis.

Suppose there is no such analysis point. The previous work is equivalent to white, although the XML file was scanned, but not saved ..... The main function of the corresponding characters event method of this analysis point is to save the contents of the XML file read by Sax.

In detail, <book is the "12" in ...>12</book>.

public void characters (char[] ch, int start, int length) throws Saxexception {//TODO auto-generated method Stubstringbuffe R.append (ch,start,length); super.characters (ch, start, length);}

Parsing XML using sax:

public class Mainactivity extends Activity {private list<book> books; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); InputStream Instream = Getresources (). Openrawresource (R.raw.books); Bookxmlparser parser = new Bookxmlparser () books = ((Bookxmlparser) xmltool.parse (instream, parser)). GetData (); if ( Books!=null && books.size () >0) {for (int i = 0;i<books.size (); i++) {log.d ("AAA", Books.get (i). toString ()) ;}}}}


Write an XML file

public static void WriteXML (List<book> books, outputstream out) throws Exception {        XmlSerializer serializer = Xml.newserializer ();        Serializer.setoutput (out, "UTF-8");        Serializer.startdocument ("UTF-8", true);                Serializer.starttag (NULL, "books");                        for (book book:books) {Serializer.starttag (null, "book");                        Serializer.attribute (NULL, "Book:name", Book.getname ());             Serializer.attribute (NULL, "Book:id", Book.getid ());                        Serializer.attribute (NULL, "Book:price", Book.getprice ());                      Serializer.attribute (NULL, "Book:publisher", Book.getpublisher ());                        Serializer.text (String.valueof (Book.getcount ()));        Serializer.endtag (NULL, "book");        } Serializer.endtag (NULL, "books");        Serializer.enddocument ();        Out.flush ();    Out.close (); }

demo:http://download.csdn.net/detail/tangnengwu/7664719

Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Data storage (two)--sax Engine XML Memory (demo included)

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.