import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; //================================================= // File Name : MySAX //------------------------------------------------------------------------------ // Author : Common //类名:MySAX //属性: //方法: public class MySAX extends DefaultHandler{ //定义SAX解析器 public void startDocument() throws SAXException{ //文档开始 System.out.println("<?xml version="1.0" encoding="UTF-8"?>"); } public void endDocument() throws SAXException{ //文档结束 System.out.println(" 文档读取结束。。。"); } public void startElement(String uri,String localName,String name,Attributes attributes) throws SAXException{ System.out.print("<"); System.out.print(name); if(attributes != null){ for(int i=0;i<attributes.getLength();i++){ System.out.print(" "+attributes.getQName(i)+"=""+attributes.getValue(i)+"""); } System.out.print(">"); } } public void character(char[] ch,int start,int lenght) throws SAXException{ System.out.print(new String(ch,start,lenght)); } public void endElement(String uri,String localName,String name) throws SAXException{ System.out.print("</"); System.out.print(name); System.out.print(">"); } }
import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; //================================================= // File Name : testSAX //------------------------------------------------------------------------------ // Author : Common public class testSAX { public static void main(String[] args) throws Exception{ // TODO 自动生成的方法存根 //建立SAX解析工厂 SAXParserFactory factory = SAXParserFactory.newInstance(); //构造解析器 SAXParser parser = factory.newSAXParser(); //解析XML,使用HANDLER parser.parse("/home/common/software/coding/HelloWord/JavaWeb/bin/dom_name.xml", new MySAX()); } }