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>
1、使用DOM(JAXP Crimson解析器)
实现方法:
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文档来构造层次结构,消耗资源大。
2. 使用SAX
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);}
}
【优点】
①不需要等待所有数据都被处理,分析就能立即开始。
②只在读取数据时检查数据,不需要保存在内存中。
③可以在某个条件得到满足时停止解析,不必解析整个文档。
④效率和性能较高,能解析大于系统内存的文档。
①需要应用程序自己负责TAG的处理逻辑(例如维护父/子关系等),文档越复杂程序就越复杂。
②单向导航,无法定位文档层次,很难同时访问同一文档的不同部分数据,不支持XPath。
3、使用JDOM
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();
}
}
【优点】
①使用具体类而不是接口,简化了DOM的API。
②大量使用了Java集合类,方便了Java开发人员。
①没有较好的灵活性。
②性能较差。
4、使用DOM4J
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();
}
)
【优点】
①大量使用了Java集合类,方便Java开发人员,同时提供一些提高性能的替代方法。
②支持XPath。
③有很好的性能。
①大量使用了接口,API较为复杂。
4种方法综合对比
读取XML配置文件
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();
}
}
在XML文件中增加节点
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();
}
}
在XML中修改节点信息
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();
}
}
删除XML中的节点
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();
}
}
作者:冒牌SEO,如若转载,请注明出处:https://www.web176.com/java/15266.html