1. Sax概述
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;
sdk源码查看路径(google code)
Sax 创建和解析 XML 的效果图:
2、Sax 创建 XML
首先,SAXTransformerFactory.newInstance() 创建一个工厂实例 factory
接着,factory.newTransformerHandler() 获取 TransformerHandler 的 handler 对象
然后,通过 handler 事件创建handler.getTransformer()、 handler.setResult(result),以及 startDocument()、startElement、characters、endElement、endDocument()等
Code
/** Sax方式,创建 XML */ public String saxCreateXML(){ StringWriter xmlWriter = new StringWriter(); Person []persons = new Person[3]; // 创建节点Person对象 persons[0] = new Person(1, "sunboy_2050", "http://blog.csdn.net/sunboy_2050"); persons[1] = new Person(2, "baidu", "http://www.baidu.com"); persons[2] = new Person(3, "google", "http://www.google.com"); try { SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler = factory.newTransformerHandler(); Transformer transformer = handler.getTransformer(); // 设置xml属性 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); StreamResult result = new StreamResult(xmlWriter); // 保存创建的xml handler.setResult(result); handler.startDocument(); AttributesImpl attr = new AttributesImpl(); attr.clear(); attr.addAttribute("", "", "author", "", "homer"); attr.addAttribute("", "", "date", "", "2012-04-27"); handler.startElement("", "", "root", attr); int personsLen = persons.length; for(int i=0; i<personsLen; i++){ attr.clear(); handler.startElement("", "", "person", attr); attr.clear(); handler.startElement("", "", "id", attr); String id = persons[i].getId() + ""; handler.characters(id.toCharArray(), 0, id.length()); handler.endElement("", "", "id"); attr.clear(); handler.startElement("", "", "name", attr); String name = persons[i].getName(); handler.characters(name.toCharArray(), 0, name.length()); handler.endElement("", "", "name"); attr.clear(); handler.startElement("", "", "blog", attr); String blog = persons[i].getBlog(); handler.characters(blog.toCharArray(), 0, blog.length()); handler.endElement("", "", "blog"); handler.endElement("", "", "person"); } handler.endElement("", "", "root"); handler.endDocument(); } catch (TransformerFactoryConfigurationError e) { // SAXTransformerFactory.newInstance e.printStackTrace(); } catch (TransformerConfigurationException e) { // factory.newTransformerHandler e.printStackTrace(); } catch (IllegalArgumentException e) { // transformer.setOutputProperty e.printStackTrace(); } catch (SAXException e) { // handler.startDocument e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } savedXML(fileName, xmlWriter.toString()); return xmlWriter.toString(); }
运行结果:
3、Sax解析XML
Code
/** Sax方式,解析 XML */ public String saxResolveXML(){ StringWriter xmlWriter = new StringWriter(); InputStream is = readXML(fileName); try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); PersonHandler handler = new PersonHandler(); // person处理Handler saxParser.parse(is, handler); // handler解析xml // 获取解析的xml String xmlHeader = handler.getXMLHeader(); xmlWriter.append(xmlHeader); List<Person> personsList = handler.getPersons(); int personsLen = personsList.size(); for(int i=0; i<personsLen; i++){ xmlWriter.append(personsList.get(i).toString()).append("\n"); } } catch (FactoryConfigurationError e) { // SAXParserFactory.newInstance e.printStackTrace(); } catch (ParserConfigurationException e) { // factory.newSAXParser e.printStackTrace(); } catch (SAXException e) { // factory.newSAXParser e.printStackTrace(); } catch (IllegalArgumentException e) { // saxParser.parse e.printStackTrace(); } catch (IOException e) { // saxParser.parse e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return xmlWriter.toString(); } /** 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 xmlHeader.toString(); } /** 返回解析的Person实例数组 */ public List<Person> getPersons(){ return personsList; } @Override public void startDocument() throws SAXException{ super.startDocument(); personsList = new ArrayList<Person>(); xmlHeader = new StringBuffer(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{ super.startElement(uri, localName, qName, attributes); if("root".equals(localName)) { String attrAuthor = attributes.getValue(0); String attrDate = attributes.getValue(1); xmlHeader.append("root").append("\t\t"); xmlHeader.append(attrAuthor).append("\t"); xmlHeader.append(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 { super.characters(ch, start, length); if (null != tag) { String value = new String(ch, start, length); System.out.println("value = " + value); if ("id".equals(tag)) { person.setId(new Integer(value)); } else if ("name".equals(tag)) { person.setName(value); } else if ("blog".equals(tag)) { person.setBlog(value); } } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if("person".equals(qName)) { personsList.add(person); person = null; } tag = null; super.endElement(uri, localName, qName); } @Override public void endDocument() throws SAXException{ // personsList = null; super.endDocument(); } }
4、Person类
请参见前面博客 Android 创建与解析XML(二)—— Dom方式 【4、Person类】
代码下载
参考推荐:
javax.xml.transform.sax
javax.xml.parsers
org.xml.sax
TransformerHandler
sax创建xml
Android 解析XML 之SAX