Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android創建與解析XML(三)——詳解Sax方式

Android創建與解析XML(三)——詳解Sax方式

編輯:關於Android編程

1. Sax概述

SAX是一種占用內存少且解析速度快的解析器,它采用的是事件啟動,不需要解析完整個文檔,而是按照內容順序看文檔某個部分是否符合xml語法,如果符合就觸發相應的事件,所謂的事件就是些回調方法(callback),這些方法 定義在ContentHandler中,下面是其主要方法:

startDocument():當遇到文檔的時候就觸發這個事件 調用這個方法 可以在其中做些預處理工作,如:申請對象資源

endDocument():當結束文檔的時候就觸發這個事件 調用這個方法 可以在其中做些善後工作,如:釋放申請的對象資源

startElement(String namespaceURI, String localName, String qName, Attributes atts):當遇開始標簽的時候就會觸發這個方法。

endElement(String uri, String localName, String name):當遇到結束標簽時觸發這個事件,調用此法可以做些善後工作。

charachers(char [] ch, int start, int length):當遇到xml內容時觸發這個方法,用new String(ch,start,length)可以接受內容。

Sax方式創建XML,應用了標准xml構造器 javax.xml.transform.sax.TransformerHandler 事件來創建 XML 文檔,需要導入以下內容

javax.xml.transform

  • javax.xml.transform.sax.SAXTransformerFactory;
  • javax.xml.transform.sax.TransformerHandler;
  • javax.xml.transform.Transformer;
  • javax.xml.transform.TransformerConfigurationException;
  • javax.xml.transform.TransformerFactoryConfigurationError;
  • javax.xml.transform.OutputKeys;
  • javax.xml.transform.stream.StreamResult;
  • javax.xml.transform.sax.SAXTransformerFactory;

javax.xml.parsers

  • javax.xml.parsers.SAXParser;
  • javax.xml.parsers.SAXParserFactory;
  • javax.xml.parsers.FactoryConfigurationError;
  • javax.xml.parsers.ParserConfigurationException;

org.xml.sax

  • org.xml.sax.Attributes;
  • org.xml.sax.SAXException;
  • org.xml.sax.helpers.AttributesImpl;
  • org.xml.sax.helpers.DefaultHandler;

Sax 創建和解析 XML 的效果圖:

2、Sax 創建 XML

首先,SAXTransformerFactory.newInstance() 創建一個工廠實例 factory

接著,factory.newTransformerHandler() 獲取 TransformerHandler 的 handler 對象

然後,通過 handler 事件創建handler.getTransformer()、 handler.setResult(result),以及 startDocument()、startElement、characters、endElement、endDocument()等

/** Sax方式,創建 XML */ 
public String saxCreateXML(){ 
  StringWriter xmlWriter = new StringWriter(); 
 
  Person []persons = new Person[3];    // 創建節點Person對象 
  persons[0] = new Person(1, "sunboy_2050", "http://blogcsdnnet/sunboy_2050"); 
  persons[1] = new Person(2, "baidu", "http://wwwbaiducom"); 
  persons[2] = new Person(3, "google", "http://wwwgooglecom"); 
   
  try { 
    SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactorynewInstance(); 
    TransformerHandler handler = factorynewTransformerHandler(); 
     
    Transformer transformer = handlergetTransformer();   // 設置xml屬性 
    transformersetOutputProperty(OutputKeysINDENT, "yes"); 
    transformersetOutputProperty(OutputKeysENCODING, "utf-8"); 
    transformersetOutputProperty(OutputKeysVERSION, "0"); 
     
    StreamResult result = new StreamResult(xmlWriter);   // 保存創建的xml 
    handlersetResult(result); 
     
    handlerstartDocument(); 
    AttributesImpl attr = new AttributesImpl(); 
     
    attrclear(); 
    attraddAttribute("", "", "author", "", "homer"); 
    attraddAttribute("", "", "date", "", "2012-04-27"); 
    handlerstartElement("", "", "root", attr); 
     
    int personsLen = personslength; 
    for(int i=0; i<personsLen; i++){ 
      attrclear(); 
      handlerstartElement("", "", "person", attr); 
       
      attrclear(); 
      handlerstartElement("", "", "id", attr); 
      String id = persons[i]getId() + ""; 
      handlercharacters(idtoCharArray(), 0, idlength()); 
      handlerendElement("", "", "id"); 
 
      attrclear(); 
      handlerstartElement("", "", "name", attr); 
      String name = persons[i]getName(); 
      handlercharacters(nametoCharArray(), 0, namelength()); 
      handlerendElement("", "", "name"); 
 
      attrclear(); 
      handlerstartElement("", "", "blog", attr); 
      String blog = persons[i]getBlog(); 
      handlercharacters(blogtoCharArray(), 0, bloglength()); 
      handlerendElement("", "", "blog"); 
       
      handlerendElement("", "", "person"); 
    } 
     
    handlerendElement("", "", "root"); 
    handlerendDocument(); 
     
  } catch (TransformerFactoryConfigurationError e) {   // SAXTransformerFactorynewInstance 
    eprintStackTrace(); 
  } catch (TransformerConfigurationException e) {     // factorynewTransformerHandler 
    eprintStackTrace(); 
  } catch (IllegalArgumentException e) {   // transformersetOutputProperty 
    eprintStackTrace(); 
  } catch (SAXException e) {   // handlerstartDocument 
    eprintStackTrace(); 
  } catch (Exception e) { 
    eprintStackTrace(); 
  } 
   
  savedXML(fileName, xmlWritertoString()); 
  return xmlWritertoString(); 
} 

運行結果:

3、Sax解析XML
 

  /** Sax方式,解析 XML */ 
  public String saxResolveXML(){ 
    StringWriter xmlWriter = new StringWriter(); 
 
    InputStream is = readXML(fileName); 
    try { 
      SAXParserFactory factory = SAXParserFactorynewInstance(); 
      SAXParser saxParser = factorynewSAXParser(); 
       
      PersonHandler handler = new PersonHandler();  // person處理Handler 
      saxParserparse(is, handler);          // handler解析xml 
       
      // 獲取解析的xml 
      String xmlHeader = handlergetXMLHeader(); 
      xmlWriterappend(xmlHeader); 
       
      List<Person> personsList = handlergetPersons(); 
      int personsLen = personsListsize(); 
      for(int i=0; i<personsLen; i++){ 
        xmlWriterappend(personsListget(i)toString())append("\n"); 
      } 
       
    } catch (FactoryConfigurationError e) {     // SAXParserFactorynewInstance 
      eprintStackTrace(); 
    } catch (ParserConfigurationException e) {   // factorynewSAXParser 
      eprintStackTrace(); 
    } catch (SAXException e) {     // factorynewSAXParser 
      eprintStackTrace(); 
    } catch (IllegalArgumentException e) {   // saxParserparse 
      eprintStackTrace(); 
    } catch (IOException e) {      // saxParserparse 
      eprintStackTrace(); 
    } catch (Exception e) { 
      eprintStackTrace(); 
    } 
     
    return xmlWritertoString(); 
  } 
   
  /** Handler處理類 */ 
  private final class PersonHandler extends DefaultHandler{ 
    private List<Person> personsList = null; // 保存person 
    private Person person = null; 
    private StringBuffer xmlHeader;       // 保存xml頭部信息 
    private String tag = null;     // xml Element 
     
    /** 返回解析的xml頭部信息 */ 
    public String getXMLHeader(){ 
      return xmlHeadertoString(); 
    } 
     
    /** 返回解析的Person實例數組 */ 
    public List<Person> getPersons(){ 
      return personsList; 
    } 
     
    @Override 
    public void startDocument() throws SAXException{ 
      superstartDocument(); 
      personsList = new ArrayList<Person>(); 
      xmlHeader = new StringBuffer(); 
    } 
     
    @Override 
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{ 
      superstartElement(uri, localName, qName, attributes); 
      if("root"equals(localName)) { 
        String attrAuthor = attributesgetValue(0); 
        String attrDate = attributesgetValue(1); 
        xmlHeaderappend("root")append("\t\t"); 
        xmlHeaderappend(attrAuthor)append("\t"); 
        xmlHeaderappend(attrDate)append("\n"); 
      } else if("person"equals(localName)) { 
        person = new Person(); 
      }  
      tag = localName; 
    } 
     
    @Override 
    public void characters(char[] ch, int start, int length) throws SAXException { 
      supercharacters(ch, start, length); 
      if (null != tag) { 
        String value = new String(ch, start, length); 
        Systemoutprintln("value = " + value); 
        if ("id"equals(tag)) { 
          personsetId(new Integer(value)); 
        } else if ("name"equals(tag)) { 
          personsetName(value); 
        } else if ("blog"equals(tag)) { 
          personsetBlog(value); 
        } 
      } 
    } 
     
    @Override 
    public void endElement(String uri, String localName, String qName) throws SAXException { 
      if("person"equals(qName)) { 
        personsListadd(person); 
        person = null; 
      } 
      tag = null; 
      superendElement(uri, localName, qName); 
    } 
     
    @Override 
    public void endDocument() throws SAXException{ 
//     personsList = null; 
      superendDocument(); 
    } 
  } 

運行結果:

4、Person類

請參見前文Android 創建與解析XML(二)—— Dom方式 【4、Person類】

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved