package ls.xml;
import java.io.StreamCorruptedException;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserHandler extends DefaultHandler {
//遍历xml文件的开始标签
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(qName.equals("book")){
System.out.println("================开始遍历一本书===============");
//System.out.println("book的属性值:"+attributes.getValue("id"));
int num = attributes.getLength();
for (int i = 0; i < num; i++) {
System.out.println("book的第"+(i+1)+"个属性"+attributes.getQName(i)+"--属性值:"+attributes.getValue(i));
}
}else if(!qName.equals("book")&&!qName.equals("bookstore")){
System.out.print("节点名是:"+qName);
}
}
//遍历xml文件的结束标签
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
//判断一本书结束
if(qName.equals("book")){
System.out.println("================结束遍历一本书===============");
}
}
//标志解析开始
@Override
public void startDocument() throws SAXException {
super.startDocument();
System.out.println("SAX解析开始");
}
//标志解析结束
@Override
public void endDocument() throws SAXException {
super.endDocument();
System.out.println("SAX解析结束");
}
//获取节点值,自动调用
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
String value = new String(ch,start,length);
if(!value.trim().equals(""))
System.out.println("--节点值是:"+value);
}
}