package com.bird.sax;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
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;
/**
* @use SAX解析
* @author Bird
*
*/
public class XmlReader {
public static void main(String [] args) throws Exception{
// 获得工厂
SAXParserFactory factory = SAXParserFactory.newInstance();
//获得解析器
SAXParser sp = factory.newSAXParser();
//获取读取器
XMLReader reader = sp.getXMLReader();
//设置内容处理器
reader.setContentHandler(new ValuesHandle());
//读取XML文档的内容
reader.parse("d://book.xml");
}
}
class ValuesHandle extends DefaultHandler{//只解析作者的名字
private String currentTag ;//记住当前想要解析的标签
private int needNumber = 2;//记住你想要的标签的位置
private int currentNumber; //当前解析的是第几个
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if("作者".equals(currentTag) && currentNumber == needNumber){
System.out.println(new String(ch,start,length));
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentTag = null;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentTag = qName;
if(currentTag.equals("作者")){
currentNumber++;
}
}
}
class ListHandle implements ContentHandler{
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.println(new String(ch,start,length));
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
// TODO Auto-generated method stub
}
@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 setDocumentLocator(Locator locator) {
// TODO Auto-generated method stub
}
@Override
public void skippedEntity(String name) throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void startDocument() 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 values = atts.getValue(i);
System.out.println(name + " " + values);
}
}
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
// TODO Auto-generated method stub
}
}
SAX解析XML文档
最新推荐文章于 2024-11-08 09:48:14 发布