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);
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值