Data storage (2) -- XML storage of the SAX engine (with Demo)

Source: Internet
Author: User

Data storage (2) -- XML storage of the SAX engine (with Demo)

The Android SDK only supports reading XML using the SAX technology, and the SAX adopts the sequential reading method to process XML documents. This requires that each time you read a node of the XML document, the corresponding event is triggered to process the node. The following describes how to use SAX based on an instance:

Public class Book {private String name; private String id; private String price; private String publisher; private int count;... get, set Method omitted}

The XML file is as follows:

 
        
  
   
12
      
  
   
10
      
  
   
21
   
 


XMLTool. java

1. Build a factory SAXParserFactory
2. Construct and instantiate the SAXPraser object

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();parser.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
 
  
DataList; private Book; private StringBuffer stringBuffer = new StringBuffer (); // private StringBuffer buffer = new StringBuffer (); public ArrayList
  
   
GetData () {return dataList;} public void startDocument () throws SAXException {// TODO Auto-generated method stubdataList = new ArrayList
   
    
();} Public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {// TODO Auto-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. start Element (uri, localName, qName, attributes) ;}@ Overridepublic void characters (char [] ch, int start, int length) throws SAXException {// TODO Auto-generated method stubstringBuffer. append (ch, start, length); super. characters (ch, start, length) ;}@ Overridepublic void endElement (String uri, String localName, String qName) throws SAXException {// TODO Auto-generated method stubif (qName. equals ("book") {if (stri NgBuffer. toString ()! = Null &&! StringBuffer. toString (). equals ("") {book. setCount (Integer. parseInt (stringBuffer. toString (). trim (); stringBuffer. setLength (0); // The buffer must be cleared} dataList. add (book);} super. endElement (uri, localName, qName );}}
   
  
 

The SAX engine needs to process five analysis points, also known as analysis events.

1. Start to analyze the XML file. This analysis point indicates that the SAX engine has just started to process XML files, but has not read the content in the XML file. The analysis point corresponds:

public void startDocument() throws SAXException {// TODO Auto-generated method stubdataList = new ArrayList
 
  ();}
 

Some initialization work can be done in this method.

2. Start to process every XML element. That is This will trigger this analysis node when starting the tag. The corresponding event method is startElement. On this node, you can obtain the element name and attribute information.

public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {// TODO Auto-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. process Each XML element. That isIn this case, the endElement method is triggered to end the tag. In this event, you can obtain all information about the currently processed elements.

Public void endElement (String uri, String localName, String qName) throws SAXException {// TODO Auto-generated method stubif (qName. equals ("book") {if (stringBuffer. toString ()! = Null &&! StringBuffer. toString (). equals ("") {book. setCount (Integer. parseInt (stringBuffer. toString (). trim (); stringBuffer. setLength (0); // The buffer must be cleared} dataList. add (book);} super. endElement (uri, localName, qName );}

4. process the XML file. If the SAX engine scans all XML files, the endDocument method is triggered. This method may not be necessary, but it can complete some final work, such as releasing resources. In this example, I am not using it.

5. Read character analysis points. This is an important analysis point. Without this analysis point, the previous work is equivalent to doing it in white. Although the XML file is scanned, It is not saved ..... the characters event method corresponding to this analysis point is mainly used to save the XML file content read by SAX. Specifically 12 "12" in"

public void characters(char[] ch, int start, int length)throws SAXException {// TODO Auto-generated method stubstringBuffer.append(ch,start,length);super.characters(ch, start, length);}

Use SAX to parse XML:

Public class MainActivity extends Activity {private List
 
  
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
  
   


Write XML files

public static void WriteXML(List
    
      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

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.