SAX结合栈查找xml指定元素

package com.px.sax;

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 SaxPush extends DefaultHandler  {
	private Stack st = new Stack();// 先准备一个栈
	private String keyname;// 属性的限定名
	private String key;// 属性的值
	private String name1;//取得的name的值
	private String age1;//取得的 age的值
	
	public String getKeyname() {
		return keyname;
	}

	public void setKeyname(String keyname) {
		this.keyname = keyname;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	
	public static void main(String[] args) {
		SAXParserFactory sf = SAXParserFactory.newInstance();
		SaxPush spu=new SaxPush();
		spu.setKeyname("sn");
		spu.setKey("01");
		try {
			SAXParser sp = sf.newSAXParser();			
			File file = new File("students.xml");			
			sp.parse(file, spu);			
			
			//System.out.println("---------------" + spu.getKey()+spu.getKeyname());
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			spu.write();
			//e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
     //打出他的数据的方法
	public void write(){
		System.out.println("name="+name1);
		System.out.println("age="+age1);
	}
	@Override
	public void characters(char[] ch, int start, int length){
		//看栈内是不是为空,如果不为空  peek 查看堆栈顶部的对象 如果是name 
		if(!st.empty()){
			String s=(String)st.peek();
			if(s.equals("name")){
				name1=new String(ch,start,length);//如果是name 得到name后面的值
			}else if(s.equals("age")){
				 age1=new String(ch,start,length);//如果是age 得到age后面的值
			}
		}
	}

	//@Override
	public void endElement(String uri, String localName, String qName)throws SAXException{
		//判断如果栈不为空 弹栈 直接弹空后 已经取得了所有的值,抛出异常 中止解析
		if(!st.empty())   //若栈不为空则进入下面处理
	        {
	            if("student".equals(qName)) 
	                {
	                st.pop();
	                throw new SAXException("查找成功!"); //抛出异常中止查询
	                }
	            else
	            {
	                st.pop();
	            }
	        }
	    }



	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// 在读元素时 先看是不是学生这个元素
		
		if ("student".equals(qName)) {
			// 看它的属性 是不是和你传过来的值是不是相等 如果相等压栈
			for (int i = 0; i < attributes.getLength(); i++) {			
				if (attributes.getQName(i).equals(keyname)
						&& attributes.getValue(i).equals(key)) {
					st.push(qName);					
					
				}
			}
		}else{
			//看栈是不是为空 不为空直接压栈
			if(!st.empty()){
				st.push(qName);
			}
		}
	}
}

你可能感兴趣的:(xml)