XML (eXtensible Markup Language) 意为可扩展标记语言,被多数技术人员用以选择作为数据传输的载体,成为一种通用的数据交换格式,xml的平台无关性,语言无关性,系统无关性,给数据集成与交互带来了极大的便利。在不同的语言中,解析xml的方式都是一样的,只不过实现的语法不同而已。众所周知,现在解析XML的方法越来越多,但主流的方法也就四种,即:DOM、SAX、JDOM和DOM4J。
这四种方法的jar包下载地址:
①DOM:在现在的Java JDK里都自带了,在xml-apis.jar包里
②SAX:http://sourceforge.net/projects/sax/
③JDOM:http://jdom.org/downloads/index.html
④DOM4J:http://sourceforge.net/projects/dom4j/
下面以一个实例来具体说明这4种方法:
xml文件:
<?xml version="1.0" encoding="GB2312"?>
<RESULT>
<VALUE>
<NO>A1234</NO>
<ADDR>四川省XX县XX镇XX路X段XX号</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR>四川省XX市XX乡XX村XX组</ADDR>
</VALUE>
</RESULT>
实现方法:
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class MyXMLReader{
public static void main(String arge[]){
long lasting =System.currentTimeMillis();
try{
File f=new File("data_10k.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc = builder.parse(f);
NodeList nl = doc.getElementsByTagName("VALUE");
for (int i=0;i<nl.getLength();i++){
System.out.print("车牌号码:" + doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue());
System.out.println("车主地址:" + doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue());
}
}catch(Exception e){
e.printStackTrace();
}
【优点】
【缺点】
通常需要加载整个XML文档来构造层次结构,消耗资源大。
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
public class MyXMLReader extends DefaultHandler {
java.util.Stack tags = new java.util.Stack();
public MyXMLReader() {
super();
}
public static void main(String args[]) {
long lasting = System.currentTimeMillis();
try {
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
MyXMLReader reader = new MyXMLReader();
sp.parse(new InputSource("data_10k.xml"), reader);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("运行时间:" + (System.currentTimeMillis() - lasting) + "毫秒");}
public void characters(char ch[], int start, int length) throws SAXException {
String tag = (String) tags.peek();
if (tag.equals("NO")) {
System.out.print("车牌号码:" + new String(ch, start, length));
}
if (tag.equals("ADDR")) {
System.out.println("地址:" + new String(ch, start, length));
}
}
public void startElement(String uri,String localName,String qName,Attributes attrs) {
tags.push(qName);}
}
【优点】
import java.io.*;
import java.util.*;
import org.jdom.*;
import org.jdom.input.*;
public class MyXMLReader {
public static void main(String arge[]) {
long lasting = System.currentTimeMillis();
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("data_10k.xml"));
Element foo = doc.getRootElement();
List allChildren = foo.getChildren();
for(int i=0;i<allChildren.size();i++) {
System.out.print("车牌号码:" + ((Element)allChildren.get(i)).getChild("NO").getText());
System.out.println("车主地址:" + ((Element)allChildren.get(i)).getChild("ADDR").getText());
}
} catch (Exception e) {
e.printStackTrace();
}
}
【优点】
import java.io.*;
import java.util.*;
import org.dom4j.*;
import org.dom4j.io.*;
public class MyXMLReader {
public static void main(String arge[]) {
long lasting = System.currentTimeMillis();
try {
File f = new File("data_10k.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(f);
Element root = doc.getRootElement();
Element foo;
for (Iterator i = root.elementIterator("VALUE"); i.hasNext() {
foo = (Element) i.next();
System.out.print("车牌号码:" + foo.elementText("NO"));
System.out.println("车主地址:" + foo.elementText("ADDR"));
}
} catch (Exception e) {
e.printStackTrace();
}
)
【优点】
DocumentBuilderFactory
dbf=DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlPath); // 使用dom解析xml文件
NodeList sonlist = doc.getElementsByTagName("son");
for (int i = 0; i < sonlist.getLength(); i++) // 循环处理对象
{
Element son = (Element)sonlist.item(i);;
for (Node node = son.getFirstChild(); node != null; node = node.getNextSibling()){
if (node.getNodeType() == Node.ELEMENT_NODE){
String name = node.getNodeName();
String value = node.getFirstChild().getNodeValue();
System.out.println(name+" : "+value);
}
}
}
public static void getFamilyMemebers(){
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlPath); // 使用dom解析xml文件
NodeList sonlist = doc.getElementsByTagName("son");
for (int i = 0; i < sonlist.getLength(); i++) // 循环处理对象
{
Element son = (Element)sonlist.item(i);;
for (Node node = son.getFirstChild(); node != null; node = node.getNextSibling()){
if (node.getNodeType() == Node.ELEMENT_NODE){
String name = node.getNodeName();
String value = node.getFirstChild().getNodeValue();
System.out.println(name+" : "+value);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Element root = xmldoc.getDocumentElement();
//删除指定节点
Element son =xmldoc.createElement("son");
son.setAttribute("id", "004");
Element name = xmldoc.createElement("name");
name.setTextContent("小儿子");
son.appendChild(name);
Element age = xmldoc.createElement("name");
age.setTextContent("0");
son.appendChild(age);
root.appendChild(son);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former = factory.newTransformer();
former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath)));
public static void createSon() {
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(false);
try{
DocumentBuilder db=dbf.newDocumentBuilder();
Document xmldoc=db.parse(xmlPath);
Element root = xmldoc.getDocumentElement();
//删除指定节点
Element son =xmldoc.createElement("son");
son.setAttribute("id", "004");
Element name = xmldoc.createElement("name");
name.setTextContent("小儿子");
son.appendChild(name);
Element age = xmldoc.createElement("name");
age.setTextContent("0");
son.appendChild(age);
root.appendChild(son);
//保存
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former = factory.newTransformer();
former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath)));
}catch(Exception e){
e.printStackTrace();
}
}
public static Node selectSingleNode(String express, Element source) {
Node result=null;
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
try {
result=(Node) xpath.evaluate(express, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
}
Element root = xmldoc.getDocumentElement();
Element per =(Element) selectSingleNode("/father/son[@id='001']", root);
per.getElementsByTagName("age").item(0).setTextContent("27");
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former = factory.newTransformer();
former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath)));
public static void modifySon(){
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
try{
DocumentBuilder db=dbf.newDocumentBuilder();
Document xmldoc=db.parse(xmlPath);
Element root = xmldoc.getDocumentElement();
Element per =(Element) selectSingleNode("/father/son[@id='001']", root);
per.getElementsByTagName("age").item(0).setTextContent("27");
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former = factory.newTransformer();
former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath)));
}catch(Exception e){
e.printStackTrace();
}
}
Element root = xmldoc.getDocumentElement();
Element son =(Element) selectSingleNode("/father/son[@id='002']", root);
root.removeChild(son);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former = factory.newTransformer();
former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath)));
public static void discardSon(){
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
try{
DocumentBuilder db=dbf.newDocumentBuilder();
Document xmldoc=db.parse(xmlPath);
Element root = xmldoc.getDocumentElement();
Element son =(Element) selectSingleNode("/father/son[@id='002']", root);
root.removeChild(son);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former = factory.newTransformer();
former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath)));
}catch(Exception e){
e.printStackTrace();
}
}