**解析XML文件,Android 内置了三种解析方案。
SAX解析XML
1. person.xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <persons>
- <person id="23">
- <name>wjh</name>
- <age>25</age>
- </person>
- <person id="20">
- <name>wjh2</name>
- <age>30</age>
- </person>
- </persons>
2. Service:
- public class XMLParserService {
- public static List<Person> readXML(InputStream inStream) throws Exception {
- SAXParserFactory spf = SAXParserFactory.newInstance();
- SAXParser saxParser = spf.newSAXParser(); // 创建解析器
- // 设置解析器的相关特性,http://xml.org/sax/features/namespaces = true 表示开启命名空间特性
- //saxParser.setProperty("http://xml.org/sax/features/namespaces", true);
- XMLContentHandler handler = new XMLContentHandler();
- saxParser.parse(inStream, handler);
- inStream.close();
- return handler.getPersons();
- }
- }
3. ContentHandler
- public class XMLContentHandler extends DefaultHandler {
- private List<Person> persons;
- private Person person;
- private String preTag;
- @Override
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- if(preTag != null) {
- String data = new String(ch, start, length);
- if("name".equals(preTag)) {
- person.setName(data);
- } else if("age".equals(preTag)) {
- person.setAge(Short.valueOf(data));
- }
- }
- }
- @Override
- public void endElement(String uri, String localName, String qName)
- throws SAXException {
- if("person".equals(localName) && person != null) {
- persons.add(person);
- }
- preTag = null;
- }
- @Override
- public void startDocument() throws SAXException {
- persons = new ArrayList<Person>();
- }
- @Override
- public void startElement(String uri, String localName, String qName,
- Attributes attributes) throws SAXException {
- if("person".equals(localName)) {
- person = new Person();
- person.setId(Integer.parseInt(attributes.getValue(0)));
- }
- preTag = localName;
- }
- /**
- * 返回解析出的 Person 对象集合
- * @return
- */
- public List<Person> getPersons() {
- return persons;
- }
- }
DOM 解析上例的 XML 示例 :
1. Service
- public class DOMService {
- public static List<Person> readXML(InputStream inStream) throws Exception {
- List<Person> persons = new ArrayList<Person>();
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document dom = builder.parse(inStream);
- Element root = dom.getDocumentElement();
- NodeList personNodes = root.getElementsByTagName("person");
- for(int i=0; i < personNodes.getLength(); i++) {
- Person person = new Person();
- Element personNode = (Element) personNodes.item(i);
- person.setId(Integer.parseInt(personNode.getAttribute("id")));
- NodeList personChildList = personNode.getChildNodes();
- for(int j=0; j<personChildList.getLength(); j++) {
- Node node = personChildList.item(j);
- if(node.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element) node;
- if("name".equals(element.getNodeName())) {
- person.setName(element.getFirstChild().getNodeValue());
- } else if ("age".equals(element.getNodeName())) {
- person.setAge(Short.valueOf(element.getFirstChild().getNodeValue()));
- }
- }
- }
- persons.add(person);
- }
- return persons;
- }
- }
解析后返回解析的 Person 集合,任务完毕。
**Pull 解析上例的 XML 示例 (推荐):
- public static List<Person> readXML(InputStream is) throws Exception {
- List<Person> persons = null;
- Person person = null;
- XmlPullParser pullParser = Xml.newPullParser();
- pullParser.setInput(is, "UTF-8");
- int eventType = pullParser.getEventType(); // 触发第一个事件
- while (eventType != XmlPullParser.END_DOCUMENT) { // 如果不为文档结束事件
- switch (eventType) {
- case XmlPullParser.START_DOCUMENT: // 文档开始事件
- persons = new ArrayList<Person>();
- break;
- case XmlPullParser.START_TAG: // 标签开始事件
- if ("person".equals(pullParser.getName())) {
- int id = Integer.parseInt(pullParser.getAttributeValue(0));
- person = new Person();
- person.setId(id);
- }
- if (person != null) {
- if ("name".equals(pullParser.getName())) { // 读取到 name 标签
- person.setName(pullParser.nextText());
- }
- if ("age".equals(pullParser.getName())) { // 读取到 age 标签
- person.setAge((Short.valueOf((pullParser.nextText()))));
- }
- }
- break;
- case XmlPullParser.END_TAG: // 标签结束事件
- if ("person".equals(pullParser.getName())) {
- persons.add(person);
- person = null;
- }
- break;
- }
- eventType = pullParser.next();
- }
- return persons;
- }
** Pull 解析器生成 XML 文件
- public static void save(List<Person> persons, OutputStream os) throws Exception {
- XmlSerializer serializer = Xml.newSerializer();
- serializer.setOutput(os, "UTF-8");
- // 第二个参数:此 XML 是否可独立存在
- serializer.startDocument("UTF-8", true);
- // 第一个参数:命名空间,无则为null
- serializer.startTag(null, "persons");
- for(Person person : persons) {
- serializer.startTag(null, "person");
- serializer.attribute(null, "id", person.getId().toString());
- serializer.startTag(null, "name");
- serializer.text(person.getName());
- serializer.endTag(null, "name");
- serializer.startTag(null, "age");
- serializer.text(person.getAge().toString());
- serializer.endTag(null, "age");
- serializer.endTag(null, "person");
- }
- serializer.endTag(null, "persons");
- serializer.endDocument();
- }