Android 创立与解析XML(二)—— Dom方法

时间:2022-08-02 20:32:55

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的后果图:

Android 创立与解析XML(二)—— Dom方法



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

运行结果:


Android 创立与解析XML(二)—— Dom方法



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

运行成果:


Android 创立与解析XML(二)—— Dom方法



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



代码下载



参考推举:

org.w3c.dom

javax.xml.parsers

javax.xml.transform


dom创建xml

java dom创建xml