Java解析XML

对于XML本身的语法知识与技术细节,需要阅读相关的技术文献,这里面包括的内容有DOM(Document Object Model),DTD(Document Type Definition),SAX(Simple API for XML),XSD(Xml Schema Definition),XSLT(Extensible Stylesheet Language Transformations)

Java解析XML一般有四种方法:DOM、SAX、JDOM、DOM4J。基本的解析方式是DOM、SAX,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; 
//定义XML文档建立与解析的接口  
public interface XmlDocument { 
/** 
* 建立XML文档 
* @param fileName 文件全路径名称 
*/ 
public void createXml(String fileName); 
/** 
* 解析XML文档 
* @param fileName 文件全路径名称 
*/ 
public void parserXml(String fileName); 
}



1)、DOM
(1)简介

由W3C(org.w3c.dom)提供的接口,它将整个XML文档读入内存,构建一个DOM树来对各个节点(Node)进行操作。优点就是整个文档都一直在内存中,我们可以随时访问任何节点,并且对树的遍历也是比较熟悉的操作;缺点则是耗内存,并且必须等到所有的文档都读入内存才能进行处理。

(2)元素(Element)和结点(Node)的区别(org.w3c.dom)
Node对象是整个文档对象模型的主要数据类型,是DOM中最基本的对象,代表了文档树中的抽象节点。但在实际使用中很少会直接使用Node对象,而是使用Node对象的子对象Element,Attr,Text等。
Element对象表示HTML或XML文档中的一个元素,是Node类最主要的子对象,在元素中可以包含属性,因而Element中有存取其属性的方法。
Element是从Node继承而来的,元素是一个小范围的定义,必须是含有完整信息的结点才是一个元素,例如<div>...</div>。但是一个结点不一定是一个元素,而一个元素一定是一个结点。
node有几个子类型:Element,Text,Attribute,RootElement,Comment,Namespace等

(3)实例

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

为解决DOM的问题,出现了SAX。SAX ,事件驱动。当解析器发现元素开始、元素结束、文本、文档的开始或结束等时,发送事件,程序员编写响应这些事件的代码,保存数据。优点:不用事先调入整个文档,占用资源少;SAX解析器代码比DOM解析器代码小,适于Applet,下载。缺点:不是持久的;事件过后,若没保存数据,那么数据就丢了;无状态性;从事件中只能得到文本,但不知该文本属于哪个元素;使用场合:Applet;只需XML文档的少量内容,很少回头访问;机器内存少;

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)、JDOM

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

4)、DOM4J

dom4j是目前在xml解析方面是最优秀的(Hibernate、Sun的JAXM也都使用dom4j来解析XML),它合并了许多超出基本XML文档表示的功能,包括集成的XPath支持、XML Schema支持以及用于大文档或流化文档的基于事件的处理。

5)XPATH
XPath是一门在XML文档中查找信息的语言。XPath用于在XML文档中通过元素和属性进行导航。





参考:

http://developer.51cto.com/art/200903/117512.htm

http://www.jb51.net/article/46893.htm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值