XML解析之SAX解析

package xml;

import java.io.File;
import java.io.IOException;
import java.util.Stack;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLParserSAX extends DefaultHandler{

	private Stack stack = new Stack();
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser sax = factory.newSAXParser();
			
			File file = new File("C:/Users/Administrator/Desktop/TestXml.xml");
			
			sax.parse(file, new XMLParserSAX());
			
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void startDocument()throws SAXException
	{
		System.out.println("....startDocument....");
			super.startDocument();
	
	}
	
	public void endDocument()throws SAXException
	{
		System.out.println("....endDocument....");
			super.endDocument();
	
	}
	
	public void startElement(String uri,String localName,String name,Attributes attributes)throws SAXException
	{
		stack.push(name);
		
		String id = attributes.getValue("id");
		
		System.out.println(name + " : " + id);
	} 
	
	public void endElement(String uri,String localName,String name,Attributes attributes)throws SAXException
	{
		stack.pop();
	
	} 
	
	public void characters(char[] ch ,int start,int length){
		String value = new String(ch,start,length);
		String name = (String) stack.peek();
	
			System.out.println(name+ ":"+value);
		
	}
}

 

你可能感兴趣的:(C++,c,xml,C#)