使用JAXP 对 XML文档进行 SAX解析:
public class Demo1 { /**
* 使用JAXP对XML文档进行SAX解析
* @throws Exception
* @throws ParserConfigurationException
*/
public static void main(String[] args) throws ParserConfigurationException, Exception { //1.创建解析工厂
SAXParserFactory factory = SAXParserFactory.newInstance(); //2.得到解析器
SAXParser sp = factory.newSAXParser(); //3.得到读取器
XMLReader reader = sp.getXMLReader(); //4.设置内容处理器
ListHandler handler = new ListHandler();
reader.setContentHandler(handler); //5.读取XML文档内容
reader.parse("src/book.xml");
} } //得到XML文档所有内容
class ListHandler implements ContentHandler { @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++) { //防止某些时候属性值为空时,抛异常 所以再加个条件atts != null
String attName = atts.getQName(i);
String attValue = atts.getValue(i);
System.out.println(attName + "=" + attValue);
} } @Override
public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.println(new String(ch,start,length)); } @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.println("</" + qName + ">"); } @Override
public void setDocumentLocator(Locator locator) { } @Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub } @Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub } @Override
public void startPrefixMapping(String prefix, String uri)
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 skippedEntity(String name) throws SAXException {
// TODO Auto-generated method stub } }