Android创建与解析XML(二)——详解Dom方式

作者:阳光岛主 时间:2023-08-20 02:30:05 

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的效果图:
Android创建与解析XML(二)——详解Dom方式

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();
}

运行结果:
Android创建与解析XML(二)——详解Dom方式

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();
}

运行结果:
Android创建与解析XML(二)——详解Dom方式

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";
 }
}

来源:http://blog.csdn.net/sunboy_2050/article/details/7516058

标签:android,dom,xml
0
投稿

猜你喜欢

  • 在idea中显示springboot面板的方法

    2022-01-02 22:00:57
  • Java使用5个线程计算数组之和

    2022-07-25 21:41:37
  • Android编程中的5种数据存储方式

    2022-04-22 07:05:09
  • Java初学者问题图解(动力节点Java学院整理)

    2023-10-15 18:06:11
  • Java实现中英文词典功能

    2021-06-20 18:25:56
  • Mybatis的mapper.xml中if标签test判断的用法说明

    2023-12-23 23:04:16
  • Android AndFix热修复原理详情

    2023-03-02 09:17:07
  • Java数据结构之栈与队列实例详解

    2021-05-29 03:25:13
  • SpringBoot如何返回Json数据格式

    2023-01-12 16:28:51
  • 实例讲解Java 自旋锁

    2021-09-17 09:38:50
  • Android编程实现二级下拉菜单及快速搜索的方法

    2021-06-17 23:23:07
  • Android截屏保存png图片的实例代码

    2022-01-26 16:10:11
  • MyBatisPlus 大数据量查询慢的问题解决

    2022-06-17 05:56:39
  • 使用开源项目JAVAE2 进行视频格式转换

    2023-11-08 07:18:24
  • 解析C#中的常量及如何在C#编程中定义常量

    2022-03-20 22:58:36
  • Java中异常处理之try和catch代码块的使用

    2021-11-21 13:30:23
  • java多线程累加计数的实现方法

    2021-07-19 12:10:36
  • 深入讲解基于JDK的动态代理机制

    2022-07-19 07:13:32
  • java版微信公众平台消息接口应用示例

    2022-10-04 10:22:58
  • spring boot mybatis枚举映射示例代码

    2023-03-01 11:45:51
  • asp之家 软件编程 m.aspxhome.com