XML (eXtensible Markup Language) 意為可擴(kuò)展標(biāo)記語言,被多數(shù)技術(shù)人員用以選擇作為數(shù)據(jù)傳輸?shù)妮d體,成為一種通用的數(shù)據(jù)交換格式,xml的平臺無關(guān)性,語言無關(guān)性,系統(tǒng)無關(guān)性,給數(shù)據(jù)集成與交互帶來了極大的便利。在不同的語言中,解析xml的方式都是一樣的,只不過實現(xiàn)的語法不同而已。眾所周知,現(xiàn)在解析XML的方法越來越多,但主流的方法也就四種,即:DOM、SAX、JDOM和DOM4J。
這四種方法的jar包下載地址:
①DOM:在現(xiàn)在的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鎮(zhèn)XX路X段XX號</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
?。糀DDR>四川省XX市XX鄉(xiāng)XX村XX組</ADDR>
</VALUE>
</RESULT>
實現(xiàn)方法:
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();
}
【優(yōu)點】
【缺點】
通常需要加載整個XML文檔來構(gòu)造層次結(jié)構(gòu),消耗資源大。
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("運(yùn)行時間:" + (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);}
}
【優(yōu)點】
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();
}
}
【優(yōu)點】
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();
}
)
【優(yōu)點】
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++) // 循環(huán)處理對象
{
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++) // 循環(huán)處理對象
{
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();
//刪除指定節(jié)點
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();
//刪除指定節(jié)點
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();
}
}
更多建議: