您的位置:首页 > 编程语言 > Java开发

JAVA解析XML的四种方法

2009-03-31 11:12 531 查看
JAVA解析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代码 <embed height="15" width="14" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" allowscriptaccess="always" quality="high" flashvars="clipboard=package%20com.alisoft.facepay.framework.bean%3B%0A%0Aimport%20java.io.FileInputStream%3B%0Aimport%20java.io.FileNotFoundException%3B%0Aimport%20java.io.IOException%3B%0Aimport%20java.io.InputStream%3B%0A%0Aimport%20javax.xml.parsers.ParserConfigurationException%3B%0Aimport%20javax.xml.parsers.SAXParser%3B%0Aimport%20javax.xml.parsers.SAXParserFactory%3B%0A%0Aimport%20org.xml.sax.Attributes%3B%0Aimport%20org.xml.sax.SAXException%3B%0Aimport%20org.xml.sax.helpers.DefaultHandler%3B%0A%2F**%0A%20*%20%0A%20*%20%40author%20hongliang.dinghl%0A%20*%20SAX%E6%96%87%E6%A1%A3%E8%A7%A3%E6%9E%90%0A%20*%2F%0Apublic%20class%20SaxDemo%20implements%20XmlDocument%20%7B%0A%0A%09public%20void%20createXml(String%20fileName)%20%7B%0A%20%20%20%20%20%20%20%20System.out.println(%22%3C%3C%22%2Bfilename%2B%22%3E%3E%22)%3B%0A%09%7D%0A%0A%09public%20void%20parserXml(String%20fileName)%20%7B%0A%09%09SAXParserFactory%20saxfac%20%3D%20SAXParserFactory.newInstance()%3B%0A%0A%09%09try%20%7B%0A%0A%09%09%09SAXParser%20saxparser%20%3D%20saxfac.newSAXParser()%3B%0A%0A%09%09%09InputStream%20is%20%3D%20new%20FileInputStream(fileName)%3B%0A%0A%09%09%09saxparser.parse(is%2C%20new%20MySAXHandler())%3B%0A%0A%09%09%7D%20catch%20(ParserConfigurationException%20e)%20%7B%0A%0A%09%09%09e.printStackTrace()%3B%0A%0A%09%09%7D%20catch%20(SAXException%20e)%20%7B%0A%0A%09%09%09e.printStackTrace()%3B%0A%0A%09%09%7D%20catch%20(FileNotFoundException%20e)%20%7B%0A%0A%09%09%09e.printStackTrace()%3B%0A%0A%09%09%7D%20catch%20(IOException%20e)%20%7B%0A%0A%09%09%09e.printStackTrace()%3B%0A%0A%09%09%7D%0A%0A%09%7D%0A%0A%7D%0A%0Aclass%20MySAXHandler%20extends%20DefaultHandler%20%7B%0A%0A%09boolean%20hasAttribute%20%3D%20false%3B%0A%0A%09Attributes%20attributes%20%3D%20null%3B%0A%0A%09public%20void%20startDocument()%20throws%20SAXException%20%7B%0A%0A%09%09System.out.println(%22%E6%96%87%E6%A1%A3%E5%BC%80%E5%A7%8B%E6%89%93%E5%8D%B0%E4%BA%86%22)%3B%0A%0A%09%7D%0A%0A%09public%20void%20endDocument()%20throws%20SAXException%20%7B%0A%0A%09%09System.out.println(%22%E6%96%87%E6%A1%A3%E6%89%93%E5%8D%B0%E7%BB%93%E6%9D%9F%E4%BA%86%22)%3B%0A%0A%09%7D%0A%0A%09public%20void%20startElement(String%20uri%2C%20String%20localName%2C%20String%20qName%2C%0A%0A%09Attributes%20attributes)%20throws%20SAXException%20%7B%0A%0A%09%09if%20(qName.equals(%22employees%22))%20%7B%0A%0A%09%09%09return%3B%0A%0A%09%09%7D%0A%0A%09%09if%20(qName.equals(%22employee%22))%20%7B%0A%0A%09%09%09System.out.println(qName)%3B%0A%0A%09%09%7D%0A%0A%09%09if%20(attributes.getLength()%20%3E%200)%20%7B%0A%0A%09%09%09this.attributes%20%3D%20attributes%3B%0A%0A%09%09%09this.hasAttribute%20%3D%20true%3B%0A%0A%09%09%7D%0A%0A%09%7D%0A%0A%09public%20void%20endElement(String%20uri%2C%20String%20localName%2C%20String%20qName)%0A%0A%09throws%20SAXException%20%7B%0A%0A%09%09if%20(hasAttribute%20%26%26%20(attributes%20!%3D%20null))%20%7B%0A%0A%09%09%09for%20(int%20i%20%3D%200%3B%20i%20%3C%20attributes.getLength()%3B%20i%2B%2B)%20%7B%0A%0A%09%09%09%09System.out.println(attributes.getQName(0)%0A%09%09%09%09%09%09%2B%20attributes.getValue(0))%3B%0A%0A%09%09%09%7D%0A%0A%09%09%7D%0A%0A%09%7D%0A%0A%09public%20void%20characters(char%5B%5D%20ch%2C%20int%20start%2C%20int%20length)%0A%0A%09throws%20SAXException%20%7B%0A%0A%09%09System.out.println(new%20String(ch%2C%20start%2C%20length))%3B%0A%0A%09%7D%0A%0A%7D%0A" src="http://ddviplinux.javaeye.com/javascripts/syntaxhighlighter/clipboard_new.swf" lk_mediaid="lk_juiceapp_mediaPopup_1238469223829" lk_media="yes"> 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)); } }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: