sax解析是一种边读边解析,仅向前读取,不能修改,用来读。
sax创建XMLReader三步:
SAXParserFactory factory = SAXParserFactory.newInstance()
SAXParser parser = factory.newSAXParser()
XMLReader reader = parser.getXMLReader()
sax是使用类似于监听机制和适配器思想来做解析的,里面去覆盖方法:
reader.setContentHandler(new DefaultHandler(){}
具体实例代码如下:
sxaDemo
package cn.hncu.sax_stax;
import java.awt.Button;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class SaxDemo {
@Test
public void SaxDemo1() throws Exception{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader=parser.getXMLReader();
reader.setContentHandler( new DefaultHandler(){
@Override
public void startDocument() throws SAXException {
System.out.println("1 开始读取文档了....");
}
@Override
public void endDocument() throws SAXException {
System.out.println("10 文档读取结束了....");
}
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
System.out.println("一个元素开始....");
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.println("一个元素结束....");
}
});
reader.parse("./xml5/users.xml");
System.out.println("Over.....");
}
@Test
public void SaxDemo2() throws Exception{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(new DefaultHandler(){
});
reader.parse("./xml5/users.xml");
}
private String elementName="@#";
@Test
public void SaxDemo3() throws Exception{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(new DefaultHandler(){
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
if(qName.equals("user")){
String id = attributes.getValue("id");
System.out.println("id:"+id);
}else if(qName.equals("name") || qName.equals("age")){
elementName = qName;
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(qName.equals("name") || qName.equals("age")){
elementName ="@#";
}else if(qName.equals("user")){
System.out.println("--------------");
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(!elementName.equals("@#"))
System.out.println(elementName+":"+new String(ch,start,length));
}
});
reader.parse("./xml5/users.xml");
}
}
users.xml
<?xml version="1.0" encoding="utf-8"?>
<users>
<user id="A001">
<name>jack</name>
<age>23</age>
</user>
<user id="b001">
<name>Mike</name>
<age>25</age>
</user>
</users>