import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;

public class SAXTest extends DefaultHandler
{
	//打印缩进，用来美化格式
   int indent = 0;
   //当前的“主题”
   String thisTopic = "";
   //当前
   String thisElement = "";
   //构造函数
   public SAXTest()
   {
   }
   //出错处理
   public void error (SAXParseException e)
   {
      System.out.println("Error parsing the file: "+e.getMessage());
   }
   //警告信息
   public void warning (SAXParseException e)
   {
      System.out.println("Problem parsing the file: "+e.getMessage());
   }
   //严重错误
   public void fatalError (SAXParseException e)
   {
      System.out.println("Error parsing the file: "+e.getMessage());
      System.out.println("Cannot continue.");
      System.exit(1);
   }
   //文档开始
   public void startDocument() throws SAXException
   {
      System.out.println("Start Documents:");
      indent = -4;
   }
   //节点开始
   public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException
   {
	  indent = indent + 4;
      printIndent(indent);
      System.out.print("Start element: ");
      System.out.println(qName);
	  if (qName == "level")
	  {
		  printIndent(indent);
	      System.out.println("name: "+ atts.getValue("name"));
	  }
	  else if (qName == "subject")
	  {
	      thisTopic = atts.getValue("topic");
	  }
	  thisElement = qName;
   }
   //打印缩进空格
   public void printIndent(int indentSize)
   {
      for (int s = 0; s < indentSize; s++)
      {
         System.out.print(" ");
      }
   }
   //节点结束
   public void endElement(String namespaceURI,String localName,String qName) throws SAXException
   {
	   thisTopic= "";
	   thisElement = "";
	   printIndent(indent);
	   System.out.print("End element: ");
       System.out.println(qName);
       indent-=4;

   }
   //处理文本
   public void characters(char[] ch,int start,int length) throws SAXException
   {
	  if (thisElement == "subject")
	  {
	      printIndent(indent+4);
	      System.out.print(thisTopic + ": ");
	      System.out.println(new String(ch,start,length));
	  }

   }

   public static void main (String args[])
   {

      XMLReader xmlReader = null;
      SAXTest reader=new SAXTest();
	    try
	    {
        SAXParserFactory spfactory =SAXParserFactory.newInstance();
	      SAXParser SAXParser = spfactory.newSAXParser();
	      xmlReader = SAXParser.getXMLReader();
	      //设置内容处理程序
	      xmlReader.setContentHandler(reader);
	      //设置错误处理程序
	      xmlReader.setErrorHandler(reader);
	      //设置要解析的文件
	      InputSource source = new InputSource("SAXTest.xml");
	      //解析
	      xmlReader.parse(source);
	     }
	     catch (Exception e)
	     {
	      System.err.println(e);
	      System.exit(1);
	     }
    }
}
