sax解析报文

import javax.xml.parsers.ParserConfigurationException;
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;

public class SaxTest {

public static void main(String[] args) throws Exception {

//通过工厂模式获取sax对象
SAXParser sp=SAXParserFactory.newInstance().newSAXParser();
//通过sax对象拿到xml读取器
XMLReader read=sp.getXMLReader();
//设置要读取的标签
read.setContentHandler(new ContentHandler(){
//定义一个计数器
int i=0;
//定义一个标签状态
String flag="";

@Override
public void startDocument() throws SAXException {
//System.out.println("文档的开始");

}

@Override
public void startElement(String uri, String localName, String name,
Attributes atts) throws SAXException {
//System.out.println("元素的开始:"+name);
flag=name;
if(flag.equals("name")){
i++;
}
}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
//System.out.println("读取内容:"+start+":"+length);
//读取第一本书的名字
if(flag.equals("name")&&i==3){
System.out.println(new String(ch,start,length));
}
}

@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
//System.out.println("元素的结束:"+name);

}

@Override
public void endDocument() throws SAXException {
//System.out.println("文档的结束");

}

@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 startPrefixMapping(String prefix, String uri)
throws SAXException {
// TODO Auto-generated method stub

}});

//开始读取xml文档,不是把整个文档加载到read对象中的
read.parse("src/books.xml");

}

}

报文内容:

<?xml version="1.0" encoding="utf-8"?>
<books>
<book ID="BH10001" id="BH10001" haha="哈哈">
<name>java学习</name>
<price>100</price>
<author>itany</author>
</book>
<book id="BH10002">
<name>xml</name>
<price>200</price>
<author>itany</author>
</book>
<book id="BH10003">
<name>js</name>
<price>300</price>
<author>itany</author>
</book>
<book id="BH10004">
<name>jsp</name>
<price>400</price>
<author>itany</author>
</book>
<book id="BH10005">
<name>mysql</name>
<price>500</price>
<author>itany</author>
</book>
</books>

原文地址:https://www.cnblogs.com/mpxBlog/p/4498347.html