Android创建与解析XML(二)——详解Dom方式
作者:阳光岛主
本篇文章主要介绍了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;
创建和解析xml的效果图:
2、Dom 创建 XML
Dom,借助 javax.xml.parsers.DocumentBuilder,可以创建 org.w3c.dom.Document 对象。
使用来自 DocumentBuilderFactory 的 DocumentBuilder 对象在 Android 设备上创建与解析 XML 文档。您将使用 XML pull 解析器的扩展来解析 XML 文档。
/** Dom方式,创建 XML */ public String domCreateXML() { String xmlWriter = null; Person []persons = new Person[3]; // 创建节点Person对象 persons[0] = new Person(1, "sunboy_2050", "https://www.jb51.net/"); persons[1] = new Person(2, "baidu", "http://wwwbaiducom"); persons[2] = new Person(3, "google", "http://wwwgooglecom"); try { DocumentBuilderFactory factory = DocumentBuilderFactorynewInstance(); DocumentBuilder builder = factorynewDocumentBuilder(); Document doc = buildernewDocument(); Element eleRoot = doccreateElement("root"); eleRootsetAttribute("author", "homer"); eleRootsetAttribute("date", "2012-04-26"); docappendChild(eleRoot); int personsLen = personslength; for(int i=0; i<personsLen; i++) { Element elePerson = doccreateElement("person"); eleRootappendChild(elePerson); Element eleId = doccreateElement("id"); Node nodeId = doccreateTextNode(persons[i]getId() + ""); eleIdappendChild(nodeId); elePersonappendChild(eleId); Element eleName = doccreateElement("name"); Node nodeName = doccreateTextNode(persons[i]getName()); eleNameappendChild(nodeName); elePersonappendChild(eleName); Element eleBlog = doccreateElement("blog"); Node nodeBlog = doccreateTextNode(persons[i]getBlog()); eleBlogappendChild(nodeBlog); elePersonappendChild(eleBlog); } Properties properties = new Properties(); propertiessetProperty(OutputKeysINDENT, "yes"); propertiessetProperty(OutputKeysMEDIA_TYPE, "xml"); propertiessetProperty(OutputKeysVERSION, "0"); propertiessetProperty(OutputKeysENCODING, "utf-8"); propertiessetProperty(OutputKeysMETHOD, "xml"); propertiessetProperty(OutputKeysOMIT_XML_DECLARATION, "yes"); TransformerFactory transformerFactory = TransformerFactorynewInstance(); Transformer transformer = transformerFactorynewTransformer(); transformersetOutputProperties(properties); DOMSource domSource = new DOMSource(docgetDocumentElement()); OutputStream output = new ByteArrayOutputStream(); StreamResult result = new StreamResult(output); transformertransform(domSource, result); xmlWriter = outputtoString(); } catch (ParserConfigurationException e) { // factorynewDocumentBuilder eprintStackTrace(); } catch (DOMException e) { // doccreateElement eprintStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TransformerFactorynewInstance eprintStackTrace(); } catch (TransformerConfigurationException e) { // transformerFactorynewTransformer eprintStackTrace(); } catch (TransformerException e) { // transformertransform eprintStackTrace(); } catch (Exception e) { eprintStackTrace(); } savedXML(fileName, xmlWritertoString()); return xmlWritertoString(); }
运行结果:
3、Dom 解析 XML
Dom方式,解析XML是创建XML的逆过程,主要用到了builder.parse(is)进行解析,然后通过Tag、NodeList、Element、childNotes等得到Element和Node属性或值。
/** Dom方式,解析 XML */ public String domResolveXML() { StringWriter xmlWriter = new StringWriter(); InputStream is= readXML(fileName); try { DocumentBuilderFactory factory = DocumentBuilderFactorynewInstance(); DocumentBuilder builder = factorynewDocumentBuilder(); Document doc = builderparse(is); docgetDocumentElement()normalize(); NodeList nlRoot = docgetElementsByTagName("root"); Element eleRoot = (Element)nlRootitem(0); String attrAuthor = eleRootgetAttribute("author"); String attrDate = eleRootgetAttribute("date"); xmlWriterappend("root")append("\t\t"); xmlWriterappend(attrAuthor)append("\t"); xmlWriterappend(attrDate)append("\n"); NodeList nlPerson = eleRootgetElementsByTagName("person"); int personsLen = nlPersongetLength(); Person []persons = new Person[personsLen]; for(int i=0; i<personsLen; i++) { Element elePerson = (Element) nlPersonitem(i); // person节点 Person person = new Person(); // 创建Person对象 NodeList nlId = elePersongetElementsByTagName("id"); Element eleId = (Element)nlIditem(0); String id = eleIdgetChildNodes()item(0)getNodeValue(); personsetId(IntegerparseInt(id)); NodeList nlName = elePersongetElementsByTagName("name"); Element eleName = (Element)nlNameitem(0); String name = eleNamegetChildNodes()item(0)getNodeValue(); personsetName(name); NodeList nlBlog = elePersongetElementsByTagName("blog"); Element eleBlog = (Element)nlBlogitem(0); String blog = eleBloggetChildNodes()item(0)getNodeValue(); personsetBlog(blog); xmlWriterappend(persontoString())append("\n"); persons[i] = person; } } catch (ParserConfigurationException e) { // factorynewDocumentBuilder eprintStackTrace(); } catch (SAXException e) { // builderparse eprintStackTrace(); } catch (IOException e) { // builderparse eprintStackTrace(); } catch (Exception e) { eprintStackTrace(); } return xmlWritertoString(); }
运行结果:
4、Person类
Person类,是创建xml的单位实例,基于Java面向对象定义的一个类
public class Person { private int id; private String name; private String blog; public Person() { thisid = -1; thisname = ""; thisblog = ""; } public Person(int id, String name, String blog) { thisid = id; thisname = name; thisblog = blog; } public Person(Person person) { thisid = personid; thisname = personname; thisblog = personblog; } public Person getPerson(){ return this; } public void setId(int id) { thisid = id; } public int getId(){ return thisid; } public void setName(String name) { thisname = name; } public String getName() { return thisname; } public void setBlog(String blog) { thisblog = blog; } public String getBlog() { return thisblog; } public String toString() { return "Person \nid = " + id + "\nname = " + name + "\nblog = " + blog + "\n"; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。