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()等
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
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();
}
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
public String getXMLHeader(){
return xmlHeadertoString();
}
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中使用sax解析xml文件的方法Android编程解析XML方法详解(SAX,DOM与PULL)Android解析XML的三种方式SAX、Pull、Dom详解android使用SAX解析XML文件Android编程使用sax解析xml数据的方法详解详解Android之解析XML文件三种方式(DOM,PULL,SAX)Android利用SAX对XML进行增删改查操作详解