dom4j处理xml文件-saxreader与elementhandler的配合

接触到公司前辈写的有关于dom4j处理xml的代码

 

下面记录了这次自己学习测试的一小段简单实例

test1.xml

<?xml version="1.0" encoding="GB2312"?>  
<ydyf>
	<book>9901</book>
	<tuser>
		<user_autoid>9902562</user_autoid>
		<u_oid>9902179</u_oid>
		<u_ucid>151</u_ucid>
	</tuser>
	<torganization>
		<org_id>99021</org_id>
		<oname>****保健院</oname>
		<upoid>1</upoid>
	</torganization>
</ydyf>

 下面我们用到SAXReader的方式解析这个xml文件,解析大文件xml文件时,主要采用的方式就是sax方式。

    MyHandlerTest.java

 

package com.fzzy.test;

import java.io.InputStream;

import org.dom4j.ElementHandler;
import org.dom4j.io.SAXReader;

public class MyHandlerTest {
	
	SAXReader reader;
	public void test()
	{
		try
		{
			InputStream in=MyHandlerTest.class.getResourceAsStream("test1.xml");
			ElementHandler manElementHandler=(ElementHandler) new TableElementHandler();
			reader=new SAXReader();
			reader.addHandler("/ydyf/book", manElementHandler);
			reader.addHandler("/ydyf/tuser", manElementHandler);
			reader.addHandler("/ydyf/torganization", manElementHandler);
			reader.read(in);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	public static void main(String[] args)
	{
		new MyHandlerTest().test();
	}
}

    TableElementHandler.java

package com.fzzy.test;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

import org.dom4j.Element;
import org.dom4j.ElementHandler;
import org.dom4j.ElementPath;

public class TableElementHandler implements ElementHandler {

	@Override
	public void onEnd(ElementPath arg0) {
		Element row = arg0.getCurrent();
		String table = arg0.getPath().substring(6);//获得表名
		try 
		{
			if(table.equals("book"))
			{
				lsbook(row);
			}
			else if(table.equals("tuser"))
			{
				lstuser(row);
			}
			else if(table.equals("torganization"))
			{
				lstorganization(row);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}

	@Override
	public void onStart(ElementPath arg0) {	}
	public	void lsbook(Element root) throws SQLException, ParseException
	{
		System.out.println("lsbook------------");
		System.out.println(root.getQName().getName()+":"+root.getText());
		
	}
	
	public	void lstuser(Element root) throws SQLException, ParseException
	{
		System.out.println("lsbook------------");
		List<Element> list=root.elements();
		for(Element e:list)
		{
			System.out.println(e.getQName().getName()+":"+e.getText());
		}
	}
	
	public	void lstorganization(Element root) throws SQLException, ParseException
	{
		System.out.println("lsbook------------");
		List<Element> list=root.elements();
		for(Element e:list)
		{
			System.out.println(e.getText());
		}
	}
}

 

得到的结果:

lsbook------------
book:9901
lsbook------------
user_autoid:9902562
u_oid:9902179
u_ucid:151
lsbook------------
99021
****保健院
1

 

 

 

好啦,自己动手学习且写了一遍,理解的就更深刻了......

你可能感兴趣的:(handler)