使用Sax解析器对XML文件进行解析并转化为JavaBean

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014581691/article/details/47045197

     1.获取SAXParserFactory实例。

      SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();

     2.获取SAXParser实例

      SAXParser saxParser = saxParserFactory.newSAXParser();

     3.扩展DeafultHandler类,在扩展DefaultHandler的时候要把需要获取到的数据对象封装进去,然后在解析过程中逐步设置完全。实现的思路是:

        对每个标签给出对应的状态,在startElement函数中设置当前所处的状态,根据状态,在解析到数据字符的时候,将字符设置进JavaBean里面,而对于属性来说,在startElement函数中就可以直接获取到设置进入JavaBean里面了。实现如下:

JavaBean Student类:

package com.zxt.xml.sax;

/**
 * @author 赵笑天
 *
 * @time 2015年7月24日
 * 
 */
public class Student {
	private String name;
	private int age;
	private String id;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", id=" + id + "]";
	}
	
}

XML文件 student.xml

<?xml version="1.0" encoding="UTF-8"?>

<root> 
  <student id="123"> 
    <name>Olivia</name>  
    <age>20</age> 
  </student>  
  <student> 
    <name>Hyatt</name>  
    <age>21</age> 
  </student> 
</root>

实现及测试类

package com.zxt.xml.sax;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

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;

/**
 * @author 赵笑天
 *
 * @time 2015年7月24日
 * 
 */
public class SaxDemo {
	public static void main(String[] args) throws Exception{
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		SAXParser saxParser = saxParserFactory.newSAXParser();
		MyHandler mh = new MyHandler();
		saxParser.parse(new File("src/com/zxt/xml/sax/dom.xml"),mh );
		
		for (Student stu : mh.getStus()){
			System.out.println(stu);
		}
	}
}

class MyHandler extends DefaultHandler{
	
	private List<Student> stus = null; 
	
	private final int STU_STATE = 1;
	private final int NAME_STATE=2;
	private final int AGE_STATE = 3;
	
	private int currentState;
	private Student tmpStudent;
	
	public MyHandler(){
		stus = new ArrayList<Student>();
		currentState = 0 ;
	}
	
	public List<Student> getStus() {
		return stus;
	}

	public void setStus(List<Student> stus) {
		this.stus = stus;
	}

	
	@Override
	public void startElement(String uri,
            String localName,
            String qName,
            Attributes attributes)
     throws SAXException{
		if (qName.equals("student")){
			tmpStudent = new Student();
			int index = attributes.getIndex("id");
			if (index >=0){
				//属性都可以在元素开始的时候获取
				tmpStudent.setId( attributes.getValue(index));
			}
			currentState =STU_STATE;
			return ;
		}
		
		if (qName.equals("name")){
			currentState = NAME_STATE;
			return ;
		}
		
		if (qName.equals("age")){
			currentState = AGE_STATE;
			return ;
		}
	}
	
	public void characters(char[] ch,
            int start,
            int length)
     throws SAXException{
		String tmpString = new String(ch,start,length);
		if (tmpString.length() > 0){
		switch(currentState){
		case NAME_STATE:
			tmpStudent.setName(tmpString);currentState = 0 ;break;
		case AGE_STATE:
			tmpStudent.setAge(Integer.parseInt(tmpString.trim()));currentState = 0 ;break;
		default:
				break;
		}
		}
	}
	
	public void endElement(String uri,
            String localName,
            String qName)
     throws SAXException{
		if (qName.equals("student")){
			stus.add(tmpStudent);
			return ;
		}
	}
}

结果截图:



展开阅读全文

没有更多推荐了,返回首页