Android创建与解析XML(二)——Dom方式
1. Dom概述
Dom方式创建XML,应用了标准xml构造器
javax.xml.parsers.DocumentBuilder 来创建 XML 文档,需要导入以下内容
javax.xml.parsers
javax.xml.parsers.DocumentBuilder
javax.xml.parsers.DocumentBuilderFactory
javax.xml.parsers.ParserConfigurationException;
javax.xml.transform
javax.xml.transform.TransformerFactory
javax.xml.transform.Transformer
javax.xml.transform.dom.DOMSource
javax.xml.transform.stream.StreamResult
javax.xml.transform.OutputKeys;
javax.xml.transform.TransformerFactoryConfigurationError;
javax.xml.transform.TransformerConfigurationException;
javax.xml.transform.TransformerException;
org.w3c.dom
org.w3c.dom.Document;
org.w3c.dom.Element;
org.w3c.dom.Node;
org.w3c.dom.DOMException;
org.w3c.dom.NodeList;
org.xml.sax.SAXException;
sdk源码查看路径
(
google code
)
创建和解析xml的效果图:
2、Dom 创建 XML
Dom,借助 javax.xml.parsers.DocumentBuilder,可以创建 org.w3c.dom.Document 对象。
使用来自 DocumentBuilderFactory 的 DocumentBuilder 对象在 Android 设备上创建与解析 XML 文档。您将使用 XML pull 解析器的扩展来解析 XML 文档。
Code
/** Dom方式,创建 XML */ public String domCreateXML() { String xmlWriter = null; 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 { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element eleRoot = doc.createElement("root"); eleRoot.setAttribute("author", "homer"); eleRoot.setAttribute("date", "2012-04-26"); doc.appendChild(eleRoot); int personsLen = persons.length; for(int i=0; i<personsLen; i++) { Element elePerson = doc.createElement("person"); eleRoot.appendChild(elePerson); Element eleId = doc.createElement("id"); Node nodeId = doc.createTextNode(persons[i].getId() + ""); eleId.appendChild(nodeId); elePerson.appendChild(eleId); Element eleName = doc.createElement("name"); Node nodeName = doc.createTextNode(persons[i].getName()); eleName.appendChild(nodeName); elePerson.appendChild(eleName); Element eleBlog = doc.createElement("blog"); Node nodeBlog = doc.createTextNode(persons[i].getBlog()); eleBlog.appendChild(nodeBlog); elePerson.appendChild(eleBlog); } Properties properties = new Properties(); properties.setProperty(OutputKeys.INDENT, "yes"); properties.setProperty(OutputKeys.MEDIA_TYPE, "xml"); properties.setProperty(OutputKeys.VERSION, "1.0"); properties.setProperty(OutputKeys.ENCODING, "utf-8"); properties.setProperty(OutputKeys.METHOD, "xml"); properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperties(properties); DOMSource domSource = new DOMSource(doc.getDocumentElement()); OutputStream output = new ByteArrayOutputStream(); StreamResult result = new StreamResult(output); transformer.transform(domSource, result); xmlWriter = output.toString(); } catch (ParserConfigurationException e) { // factory.newDocumentBuilder e.printStackTrace(); } catch (DOMException e) { // doc.createElement e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TransformerFactory.newInstance e.printStackTrace(); } catch (TransformerConfigurationException e) { // transformerFactory.newTransformer e.printStackTrace(); } catch (TransformerException e) { // transformer.transform e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } savedXML(fileName, xmlWriter.toString()); return xmlWriter.toString(); }
运行结果:
3、Dom 解析 XML
Dom方式,解析XML是创建XML的逆过程,主要用到了builder.parse(is)进行解析,然后通过Tag、NodeList、Element、childNotes等得到Element和Node属性或值。
Code
/** Dom方式,解析 XML */ public String domResolveXML() { StringWriter xmlWriter = new StringWriter(); InputStream is= readXML(fileName); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(is); doc.getDocumentElement().normalize(); NodeList nlRoot = doc.getElementsByTagName("root"); Element eleRoot = (Element)nlRoot.item(0); String attrAuthor = eleRoot.getAttribute("author"); String attrDate = eleRoot.getAttribute("date"); xmlWriter.append("root").append("\t\t"); xmlWriter.append(attrAuthor).append("\t"); xmlWriter.append(attrDate).append("\n"); NodeList nlPerson = eleRoot.getElementsByTagName("person"); int personsLen = nlPerson.getLength(); Person []persons = new Person[personsLen]; for(int i=0; i<personsLen; i++) { Element elePerson = (Element) nlPerson.item(i); // person节点 Person person = new Person(); // 创建Person对象 NodeList nlId = elePerson.getElementsByTagName("id"); Element eleId = (Element)nlId.item(0); String id = eleId.getChildNodes().item(0).getNodeValue(); person.setId(Integer.parseInt(id)); NodeList nlName = elePerson.getElementsByTagName("name"); Element eleName = (Element)nlName.item(0); String name = eleName.getChildNodes().item(0).getNodeValue(); person.setName(name); NodeList nlBlog = elePerson.getElementsByTagName("blog"); Element eleBlog = (Element)nlBlog.item(0); String blog = eleBlog.getChildNodes().item(0).getNodeValue(); person.setBlog(blog); xmlWriter.append(person.toString()).append("\n"); persons[i] = person; } } catch (ParserConfigurationException e) { // factory.newDocumentBuilder e.printStackTrace(); } catch (SAXException e) { // builder.parse e.printStackTrace(); } catch (IOException e) { // builder.parse e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return xmlWriter.toString(); }
运行结果:
4、Person类
Person类,是创建xml的单位实例,基于Java面向对象定义的一个类
public class Person { private int id; private String name; private String blog; public Person() { this.id = -1; this.name = ""; this.blog = ""; } public Person(int id, String name, String blog) { this.id = id; this.name = name; this.blog = blog; } public Person(Person person) { this.id = person.id; this.name = person.name; this.blog = person.blog; } public Person getPerson(){ return this; } public void setId(int id) { this.id = id; } public int getId(){ return this.id; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setBlog(String blog) { this.blog = blog; } public String getBlog() { return this.blog; } public String toString() { return "Person \nid = " + id + "\nname = " + name + "\nblog = " + blog + "\n"; } }
参考推荐:
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2012-04-26 22:03:24
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!