欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java解析XML的四种方法详解

程序员文章站 2023-11-27 19:29:34
xml现在已经成为一种通用的数据交换格式,它的平台无关性,语言无关性,系统无关性,给数据集成与交互带来了极大的方便。对于xml本身的语法知识与技术细节,需要阅读相关的技术文...

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)。
复制代码 代码如下:

package com.alisoft.facepay.framework.bean;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
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;
/**
*
* @author hongliang.dinghl
* dom生成与解析xml文档
*/
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());
}
}
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文档的少量内容,很少回头访问;机器内存少;
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。

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文档。
复制代码 代码如下:

package com.alisoft.facepay.framework.bean;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.util.list;
import org.jdom.document;
import org.jdom.element;
import org.jdom.jdomexception;
import org.jdom.input.saxbuilder;
import org.jdom.output.xmloutputter;
/**
*
* @author hongliang.dinghl
* jdom 生成与解析xml文档
*
*/
public class jdomdemo implements xmldocument {
public void createxml(string filename) {
document document;
element root;
root=new element("employees");
document=new document(root);
element employee=new element("employee");
root.addcontent(employee);
element name=new element("name");
name.settext("ddvip");
employee.addcontent(name);
element sex=new element("sex");
sex.settext("m");
employee.addcontent(sex);
element age=new element("age");
age.settext("23");
employee.addcontent(age);
xmloutputter xmlout = new xmloutputter();
try {
xmlout.output(document, new fileoutputstream(filename));
} catch (filenotfoundexception e) {
e.printstacktrace();
} catch (ioexception e) {
e.printstacktrace();
}
}
public void parserxml(string filename) {
saxbuilder builder=new saxbuilder(false);
try {
document document=builder.build(filename);
element employees=document.getrootelement();
list employeelist=employees.getchildren("employee");
for(int i=0;ielement employee=(element)employeelist.get(i);
list employeeinfo=employee.getchildren();
for(int j=0;jsystem.out.println(((element)employeeinfo.get(j)).getname()+":"+((element)employeeinfo.get(j)).getvalue());
}
}
} catch (jdomexception e) {
e.printstacktrace();
} catch (ioexception e) {
e.printstacktrace();
}
}
}