package com.xml.zh;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SaxTest {
/**
* 运用Sax技术来操作xml
* @param args
* @throws SAXException
* @throws Exception
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
//1.创建SaxparseFactory
SAXParserFactory spf =SAXParserFactory.newInstance();
//2.创建Saxparser解析器
SAXParser saxparser = spf.newSAXParser();
//3.把xml文件的事件处理对象关联
saxparser.parse("src/class.xml",new defaultHander());
}
}
//定义事件处理类
class defaultHander extends DefaultHandler{
boolean isName=false;
//发现文档的文本
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
//遍历某一个元素的文本
if(!new String(ch,start,length).trim().equals("") && isName)
System.out.println(new String(ch,start,length));
//遍历
//System.out.println(new String(ch,start,length));
super.characters(ch, start, length);
}
//发现文档的结束
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
super.endDocument();
}
//发现文档的一个元素的结束
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
}
//发现文档的开始
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
super.startDocument();
}
//发现xml文档的一个元素开始
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
//System.out.println("name = "+qName);
if(qName.equals("mingzi")){
isName = true;
}else{
isName = false;
}
super.startElement(uri, localName, qName, attributes);
}
}