1、 DOM解析
DOM的全称是Document Object Model,也即文档对象模型。DOM解析会将XML文档以对象树的方式存入内存,因此,DOM解析内存消耗巨大。当然由于DOM解析将XML以节点树的方式调入内存,所以对文档进行增删改查(crud)比较方便。DOM分析器把整个XML文档转化成DOM树放在了内存中,因此,当文档比较大或者结构比较复杂时,对内存的需求就比较高。而且,对于结构复杂的树的遍历也是一项耗时的操作。所以,DOM分析器对机器性能的要求比较高,实现效率不十分理想。
-------------------------book.xml----------------------------------------------- <?xml version="1.0" encoding="UTF-8" standalone="no"?> <书架> <书> <书名>javaweb</书名> <作者>xiehe</作者> <售价>889.00元</售价> </书> <书> <书名>javaweb2</书名> <作者>hehe</作者> <售价>8.00元</售价> </书> </书架> ------------------------------------------------------------------------------------ package it.xiehe.xml; import java.io.FileOutputStream; import java.text.AttributedCharacterIterator.Attribute; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Demo02 { //1、读取xml文档内容 @Test public void read() throws Exception{ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builder.parse("src/it/xiehe/xml/book.xml"); NodeList list=document.getElementsByTagName("书名"); Node node= list.item(0); String content= node.getTextContent(); System.out.println(content); } //递归遍历节点 @Test public void read1() throws Exception{ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builder.parse("src/it/xiehe/xml/book.xml"); Node node=document.getElementsByTagName("书架").item(0); list(node); } private void list(Node node) { System.out.println(node.getTextContent()); NodeList list=node.getChildNodes(); for(int i=0;i<list.getLength();i++){ Node child=list.item(i); list(child); } } //增加一个节点 @Test public void add() throws Exception{ //1、获取document DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builder.parse("src/it/xiehe/xml/book.xml"); //2、增加节点 <售价>57.00元</售价> //1>创建节点 Element piece=document.createElement("售价"); piece.setTextContent("57.00元"); //2>把创建的节点挂到第一本书上 Element book=(Element) document.getElementsByTagName("书").item(0); book.appendChild(piece); //3将修改的xml文件回写 TransformerFactory tffactory=TransformerFactory.newInstance(); Transformer tf=tffactory.newTransformer(); tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("src/it/xiehe/xml/book.xml"))); } }
2、SAX解析
SAX的全称是Simple APIs for XML,也即XML简单应用程序接口。与DOM不同,SAX提供的访问模式是一种顺序模式,这是一种快速读写XML数据的方式。当使用SAX分析器对XML文档进行分析时,会触发一系列事件,并激活相应的事件处理函数,应用程序通过这些事件处理函数实现对XML文档的访问,因而SAX接口也被称作事件驱动接口。
需要注意的是,SAX解析XML文档时,空白不能忽略。
package it.xiehe.xml;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
public class DemoSAX {
@Test
public void test01() throws Exception, Exception {
// 1 创建sax工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
// 2 得到解析器
SAXParser parser = factory.newSAXParser();
// 3 得到读取器
XMLReader reader = parser.getXMLReader();
// 4 设置内容处理器
// 不同的功能对应不同的处理器,一般通过继承DefaultHandler覆盖其中的方法
reader.setContentHandler(new ListHandler());
// 5 读取xml文件内容
reader.parse("src/Book.xml");
}
}
//1、打印出xml文件所有内容
//通过实现ContentHandler接口对XML文档进行处理
class ListHandler implements ContentHandler{
@Override
public void setDocumentLocator(Locator locator) {
// TODO Auto-generated method stub
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
//这里对获取到的元素进行处理,暂时先输出吧!
System.out.println("<"+qName+">");
for(int i=0;atts!=null&&i<atts.getLength();i++){
String name=atts.getQName(i);
String value=atts.getValue(i);
System.out.println(name+"="+value);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
System.out.println("<"+qName+">");
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
System.out.println(new String(ch,start,length));
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void processingInstruction(String target, String data)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void skippedEntity(String name) throws SAXException {
// TODO Auto-generated method stub
}}
-------------------------------获得XML文档数据并且封装到对象中----------------------
package it.xiehe.xml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class Demo03SAX {
@Test
public void test01() throws Exception, Exception {
// 1 创建sax工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
// 2 得到解析器
SAXParser parser = factory.newSAXParser();
// 3 得到读取器
XMLReader reader = parser.getXMLReader();
// 4 设置内容处理器
BeanListHandler handler=new BeanListHandler();
reader.setContentHandler(handler);
// 5 读取xml文件内容
reader.parse("src/it/xiehe/xml/book.xml");
List<book> list=handler.getBook();
for(book b:list){
System.out.println(b);
}
}
}
// 3、打印出xml文件所有内容用book对象封装
//这里通过继承DefaultHandler类覆盖里面我们需要的方法实现想要的功能
class BeanListHandler extends DefaultHandler {
private String TagContent;//记录标签内容
private book b;//
List list = new ArrayList();//存储book对象
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
TagContent = qName;
if ("书".equals(TagContent)) {
b = new book();
}
}
public List getBook() {
return list;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if ("书名".equals(TagContent)) {
String name = new String(ch, start, length);
b.setName(name);
}