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

Android建立與解析XML(三)——詳解Sax方式
1 Star2 Stars3 Stars4 Stars5 Stars 給文章打分!
Loading...

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類】

相關文章

Android 開發 最新文章