目前XML的解析是四种,今天说一下DOM(Document Object Model)方式,我自己认为是最简单的一种,很好记~
先说几个基本概念,脑子里要有点印象;
1.什么是XML语言?
可扩展标记语言(Extensible Markup Language, XML) ,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。
2.XML的语言结构是怎样的?
1.头文件信息:
<?xml version =”1.0” encoding =”GBK” ?>
其中 version 是必须加的,而 encoding 可以不写,则默认编码是 ISO8859-1 ,不支持中文。
除了这个功能外,头信息还可以进行编写格式的规定,通过 dtd 或 xsd 文件。
2.主体信息:
元素节点和文本节点构成:
一个节点只能有一个父节点,如果没有父节点,该节点称为根节点。
一个节点可以有多个子节点。只有元素节点可以拥有子节点。
元素节点的标记必须成对出现,或直接结束。
3.DOM解析方式的优缺点? 优点:
1、允许应用程序对数据和结构做出更改。
2、访问是双向的,可以在任何时候在树中上下导航,获取和操作任意部分的数据。
缺点:
1、通常需要加载整个XML文档来构造层次结构,消耗资源大
4.代码示例
public interface XmlDocument {
/*
* 建立文档
* @param fileName 文件路径全称
*/
public void createXml(String fileName);
public void parserXml(String fileName);
}
package com.domtest.interfaces;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/*
* 为 XML 文档的已解析版本定义了一组接口。解析器读入整个文档,然后构建一个驻留内存的树结构,
* 然后代码就可以使用 DOM 接口来操作这个树结构。优点:整个文档树在内存中,便于操作;
* 支持删除、修改、重新排列等多种功能;缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;
* 使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。
*/
public class DomDemo implements XmlDocument {
private Document document;
private String fileName;
public void init() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
this.document = builder.newDocument();
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
}
}
@Override
public void createXml(String fileName) {
// TODO Auto-generated method stub
Element root = this.document.createElement("employees");
this.document.appendChild(root);
Element employee = this.document.createElement("employee");
Element name = this.document.createElement("name");
name.appendChild(this.document.createTextNode("Hello"));
employee.appendChild(name);
Element sex = this.document.createElement("sex");
sex.appendChild(this.document.createTextNode("m"));
employee.appendChild(sex);
Element age = this.document.createElement("age");
age.appendChild(this.document.createTextNode("30"));
employee.appendChild(age);
root.appendChild(employee);
TransformerFactory tf = TransformerFactory.newInstance();
try {
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
StreamResult result = new StreamResult(pw);
transformer.transform(source, result);
System.out.println(" generate xml file success!!");
} catch (TransformerConfigurationException e) {
System.out.println(e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (TransformerException e) {
System.out.println(e.getMessage());
}
}
@Override
public void parserXml(String fileName) {
// TODO Auto-generated method stub
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(fileName);
NodeList employees = document.getChildNodes();
for (int i = 0; i < employees.getLength(); i++) {
Node employee = employees.item(i);
NodeList employeeInfo = employee.getChildNodes();
for (int j = 0; j < employeeInfo.getLength(); j++) {
Node node = employeeInfo.item(j);
NodeList employeeMeta = node.getChildNodes();
for (int k = 0; k < employeeMeta.getLength(); k++) {
System.out.println(
employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getTextContent());
}
}
}
System.out.println(" 解析完毕 ");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
DomDemo dome = new DomDemo();
// dome.init();
// dome.createXml("emp1.xml");
dome.parserXml("emp1.xml");
}
}