详解Java解析XML的四种方法

来源:互联网 发布:linux while true 编辑:程序博客网 时间:2024/05/21 09:31

XML现在已经成为一种通用的数据交换格式,它的平台无关性,语言无关性,系统无关性,给数据集成与交互带来了极大的方便。对于XML本身的语法知识与技术细节,需要阅读相关的技术文献,这里面包括的内容有DOM(Document Object Model),DTD(Document Type Definition),SAX(Simple API for XML),XSD(Xml Schema Definition),XSLT(Extensible Stylesheet Language Transformations),具体可参阅w3c官方网站文档http://www.w3.org获取更多信息。

XML在不同的语言里解析方式都是一样的,只不过实现的语法不同而已。基本的解析方式有两种,一种叫SAX,另一种叫DOM。SAX是基于事件流的解析,DOM是基于XML文档树结构的解析。假设我们XML的内容和结构如下: 

<?xml version="1.0" encoding="UTF-8"?> 
<employees>
<employee>
<name>ddviplinux</name>
<sex>m</sex>
<age>30</age>
</employee>
</employees>

本文使用JAVA语言来实现DOM与SAX的XML文档生成与解析。 
首先定义一个操作XML文档的接口XmlDocument 它定义了XML文档的建立与解析的接口。

package com.alisoft.facepay.framework.bean; 
/**
*
* @author hongliang.dinghl
* 定义XML文档建立与解析的接口
*/
public interface XmlDocument {
/**
* 建立XML文档
* @param fileName 文件全路径名称
*/
public void createXml(String fileName);
/**
* 解析XML文档
* @param fileName 文件全路径名称
*/
public void parserXml(String fileName);
}

1.DOM生成和解析XML文档

为 XML 文档的已解析版本定义了一组接口。解析器读入整个文档,然后构建一个驻留内存的树结构,然后代码就可以使用 DOM 接口来操作这个树结构。

优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能;

缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;

使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。 

DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准。DOM是以 层次结构组织的节点或信息片断的集合。这个层次结构允许开发人员在树中寻找 特定信息。分析该结构通常需要加载整个文档和构造层次结构,然后才能做任何 工作。由于它是基于信息层次的,因而DOM被认为是基于树或基于对象的。DOM 以及广义的基于树的处理具有几个优点。首先,由于树在内存中是持久的,因此 可以修改它以便应用程序能对数据和结构作出更改。它还可以在任何时候在树中 上下导航,而不是像SAX那样是一次性的处理。DOM使用起来也要简单得多。

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());
}
}
public void createXml(String fileName) {
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("丁宏亮"));
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("生成XML文件成功!");
} 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());
}
}
public void parserXml(String fileName) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document 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());
}
}
}

2.SAX生成和解析XML文档

为解决DOM的问题,出现了SAX。SAX ,事件驱动。当解析器发现元素开始、元素结束、文本、文档的开始或结束等时,发送事件,程序员编写响应这些事件的代码,保存数据。

优点:不用事先调入整个文档,占用资源少;SAX解析器代码比DOM解析器代码小,适于Applet,下载。

缺点:不是持久的;事件过后,若没保存数据,那么数据就丢了;无状态性;从事件中只能得到文本,但不知该文本属于哪个元素;

使用场合:Applet;只需XML文档的少量内容,很少回头访问;机器内存少;

SAX处理的优点非常类似于流媒体的优点。分析能够立即开始,而不是等待 所有的数据被处理。而且,由于应用程序只是在读取数据时检查数据,因此不需 要将数据存储在内存中。这对于大型文档来说是个巨大的优点。事实上,应用程 序甚至不必解析整个文档;它可以在某个条件得到满足时停止解析。一般来说,SAX还比它的替代者DOM快许多。  
    选择DOM还是选择SAX? 对于需要自己编写代码来处理XML文档的开发人 员来说, 选择DOM还是SAX解析模型是一个非常重要的设计决策。 DOM采用建 立树形结构的方式访问XML文档,而SAX采用的事件模型。  
    DOM解析器把XML文档转化为一个包含其内容的树,并可以对树进行遍历。 用DOM解析模型的优点是编程容易,开发人员只需要调用建树的指令,然后利用 navigation APIs访问所需的树节点来完成任务。可以很容易的添加和修改树中 的元素。然而由于使用DOM解析器的时候需要处理整个XML文档,所以对性能和 内存的要求比较高,尤其是遇到很大的XML文件的时候。由于它的遍历能力,DOM 解析器常用于XML文档需要频繁的改变的服务中。  
    SAX解析器采用了基于事件的模型,它在解析XML文档的时候可以触发一系 列的事件,当发现给定的tag的时候,它可以激活一个回调方法,告诉该方法制 定的标签已经找到。SAX对内存的要求通常会比较低,因为它让开发人员自己来 决定所要处理的tag.特别是当开发人员只需要处理文档中所包含的部分数据 时,SAX这种扩展能力得到了更好的体现。但用SAX解析器的时候编码工作会比 较困难,而且很难同时访问同一个文档中的多处不同数据。 

Java代码

package com.alisoft.facepay.framework.bean;   
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.InputStream;  

import javax.xml.parsers.ParserConfigurationException;  
import javax.xml.parsers.SAXParser;  
import javax.xml.parsers.SAXParserFactory;  

import org.xml.sax.Attributes;  
import org.xml.sax.SAXException;  
import org.xml.sax.helpers.DefaultHandler;  
/** 
*  
* @author hongliang.dinghl 
* SAX文档解析 
*/ 
public class SaxDemo implements XmlDocument {  

public void createXml(String fileName) {  
System.out.println("<<"+filename+">>");  
}  

public void parserXml(String fileName) {  
SAXParserFactory saxfac = SAXParserFactory.newInstance();  

try {  

SAXParser saxparser = saxfac.newSAXParser();  

InputStream is = new FileInputStream(fileName);  

saxparser.parse(is, new MySAXHandler());  

} catch (ParserConfigurationException e) {  

e.printStackTrace();  

} catch (SAXException e) {  

e.printStackTrace();  

} catch (FileNotFoundException e) {  

e.printStackTrace();  

} catch (IOException e) {  

e.printStackTrace();  

}  

}  

}  

class MySAXHandler extends DefaultHandler {  

boolean hasAttribute = false;  

Attributes attributes = null;  

public void startDocument() throws SAXException {  

System.out.println("文档开始打印了");  

}  

public void endDocument() throws SAXException {  

System.out.println("文档打印结束了");  

}  

public void startElement(String uri, String localName, String qName,  

Attributes attributes) throws SAXException {  

if (qName.equals("employees")) {  

return;  

}  

if (qName.equals("employee")) {  

System.out.println(qName);  

}  

if (attributes.getLength() > 0) {  

this.attributes = attributes;  

this.hasAttribute = true;  

}  

}  

public void endElement(String uri, String localName, String qName)  

throws SAXException {  

if (hasAttribute && (attributes != null)) {  

for (int i = 0; i < attributes.getLength(); i++) {  

System.out.println(attributes.getQName(0)  
+ attributes.getValue(0));  

}  

}  

}  

public void characters(char[] ch, int start, int length)  

throws SAXException {  

System.out.println(new String(ch, start, length));  

}  


package com.alisoft.facepay.framework.bean;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author hongliang.dinghl
* SAX文档解析
*/
public class SaxDemo implements XmlDocument {
public void createXml(String fileName) {
System.out.println("<<"+filename+">>");
}
public void parserXml(String fileName) {
SAXParserFactory saxfac = SAXParserFactory.newInstance();
try {
SAXParser saxparser = saxfac.newSAXParser();
InputStream is = new FileInputStream(fileName);
saxparser.parse(is, new MySAXHandler());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MySAXHandler extends DefaultHandler {
boolean hasAttribute = false;
Attributes attributes = null;
public void startDocument() throws SAXException {
System.out.println("文档开始打印了");
}
public void endDocument() throws SAXException {
System.out.println("文档打印结束了");
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("employees")) {
return;
}
if (qName.equals("employee")) {
System.out.println(qName);
}
if (attributes.getLength() > 0) {
this.attributes = attributes;
this.hasAttribute = true;
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (hasAttribute && (attributes != null)) {
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println(attributes.getQName(0)
+ attributes.getValue(0));
}
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.println(new String(ch, start, length));
}
}

3.DOM4J生成和解析XML文档

DOM4J 是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。如今你可以看到越来越多的 Java 软件都在使用 DOM4J 来读写 XML,特别值得一提的是连 Sun 的 JAXM 也在用 DOM4J。

 为支持所有这些功能,DOM4J使用接口和抽象基本类方法。DOM4J大量使用 了API中的Collections类,但是在许多情况下,它还提供一些替代方法以允许 更好的性能或更直接的编码方法。直接好处是,虽然DOM4J付出了更复杂的API 的代价,但是它提供了比JDOM大得多的灵活性。  
    在添加灵活性、XPath集成和对大文档处理的目标时,DOM4J的目标与JDOM 是一样的:针对Java开发者的易用性和直观操作。它还致力于成为比JDOM更完 整的解决方案,实现在本质上处理所有Java/XML问题的目标。在完成该目标时, 它比JDOM更少强调防止不正确的应用程序行为。  
    DOM4J是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极 端易用使用的特点,同时它也是一个开放源代码的软件。如今你可以看到越来越 多的Java软件都在使用DOM4J来读写XML,特别值得一提的是连Sun的JAXM也 在用DOM4J. 

Java代码

package com.alisoft.facepay.framework.bean;   
import java.io.File;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.io.Writer;  
import java.util.Iterator;  

import org.dom4j.Document;  
import org.dom4j.DocumentException;  
import org.dom4j.DocumentHelper;  
import org.dom4j.Element;  
import org.dom4j.io.SAXReader;  
import org.dom4j.io.XMLWriter;  
/** 
*  
* @author hongliang.dinghl 
* Dom4j 生成XML文档与解析XML文档 
*/ 
public class Dom4jDemo implements XmlDocument {  

public void createXml(String fileName) {  
Document document = DocumentHelper.createDocument();  
Element employees=document.addElement("employees");  
Element employee=employees.addElement("employee");  
Element name= employee.addElement("name");  
name.setText("ddvip");  
Element sex=employee.addElement("sex");  
sex.setText("m");  
Element age=employee.addElement("age");  
age.setText("29");  
try {  
Writer fileWriter=new FileWriter(fileName);  
XMLWriter xmlWriter=new XMLWriter(fileWriter);  
xmlWriter.write(document);  
xmlWriter.close();  
} catch (IOException e) {  

System.out.println(e.getMessage());  
}  


}  


public void parserXml(String fileName) {  
File inputXml=new File(fileName);  
SAXReader saxReader = new SAXReader();  
try {  
Document document = saxReader.read(inputXml);  
Element employees=document.getRootElement();  
for(Iterator i = employees.elementIterator(); i.hasNext();){  
Element employee = (Element) i.next();  
for(Iterator j = employee.elementIterator(); j.hasNext();){  
Element node=(Element) j.next();  
System.out.println(node.getName()+":"+node.getText());  
}  

}  
} catch (DocumentException e) {  
System.out.println(e.getMessage());  
}  
System.out.println("dom4j parserXml");  
}   
}  

4.JDOM生成和解析XML  

为减少DOM、SAX的编码量,出现了JDOM;优点:20-80原则,极大减少了代码量。使用场合:要实现的功能简单,如解析、创建等,但在底层,JDOM还是使用SAX(最常用)、DOM、Xanan文档。

JDOM的目的是成为Java特定文档模型,它简化与XML的交互并且比使用DOM 实现更快。由于是第一个Java特定模型,JDOM一直得到大力推广和促进。正在 考虑通过“Java规范请求JSR-102”将它最终用作“Java标准扩展”。从2000 年初就已经开始了JDOM开发。  
    JDOM与DOM主要有两方面不同。首先,JDOM仅使用具体类而不使用接口。 这在某些方面简化了API,但是也限制了灵活性。第二,API大量使用了 
Collections类,简化了那些已经熟悉这些类的Java开发者的使用。    
JDOM文档声明其目的是“使用20%(或更少)的精力解决80%(或更多)Java/XML问题”(根据学习曲线假定为20%)。

JDOM自身不包含解析器。它通常使用SAX2解析器来解析和验证输入XML文 档(尽管它还可以将以前构造的DOM表示作为输入)。

   
package com.alisoft.facepay.framework.bean;   <br style="clear: both; width: 0px; height: 0px; " /><br style="clear: both; width: 0px; height: 0px; " />import java.io.FileNotFoundException;   <br style="clear: both; width: 0px; height: 0px; " />import java.io.FileOutputStream;   <br style="clear: both; width: 0px; height: 0px; " />import java.io.IOException;     
比较:  
    1)DOM4J性能最好,连Sun的JAXM也在用DOM4J.目前许多开源项目中大量 采用DOM4J,例如大名鼎鼎的Hibernate也用DOM4J来读取XML配置文件。如果 不考虑可移植性,那就采用DOM4J.  
    2)JDOM和DOM在性能测试时表现不佳,在测试10M文档时内存溢出。在小 文档情况下还值得考虑使用DOM和JDOM.虽然JDOM的开发者已经说明他们期望 在正式发行版前专注性能问题,但是从性能观点来看,它确实没有值得推荐之处。 另外,DOM仍是一个非常好的选择。DOM实现广泛应用于多种编程语言。它还是 许多其它与XML相关的标准的基础,因为它正式获得W3C推荐(与基于非标准的 Java模型相对),所以在某些类型的项目中可能也需要它(如在JavaScript中使用DOM)。  
    3)SAX表现较好,这要依赖于它特定的解析方式-事件驱动。一个SAX检 测即将到来的XML流,但并没有载入到内存(当然当XML流被读入时,会有部分 文档暂时隐藏在内存中)。 
0 0
原创粉丝点击