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运行结果:
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); List4、Person类
请参见前面博客Android 创建与解析XML(二)—— Dom方式【4、Person类】
代码下载
参考推荐:
javax.xml.transform.sax
javax.xml.parsers
org.xml.sax
TransformerHandler
sax创建xml
Android 解析XML 之SAX