利用SAXParser对XML文档进行解析处理

    SAXParser因为其对文档的处理方式,致使其可以对大型文档进行有效的处理,并且不会占用服务器太大的内存,故而可以选用这一方式对大型文档进行解析。以下为示例:

模拟解析数据

<student>
<id>1</id>
<name type="chinese">小明</name>
</student>
<student>
<id>1</id>
<name type="chinese">小美</name>
</student>
<student>
<id>1</id>
<name type="chinese">小李</name>
</student>

1.导入开始,首先创建解析工厂

public void readPolyAndPointXml(String filePath) throws Exception {
		// 创建解析工厂
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 创建解析器
		SAXParser parser = factory.newSAXParser();
		// 得到读取器
		XMLReader reader = parser.getXMLReader();
		// 设置内容处理器
		BeanListHandler handler = new BeanListHandler();
		reader.setContentHandler(handler);
		// 读取xml文档
		reader.parse(new InputSource(new FileInputStream(filePath)));
	}

2.处理内容处理器

class BeanListHandler extends DefaultHandler {
//初始化对象
List<Student> studentList = new ArrayList<>();
Student student = null;
//初始化标签
private String tag = "";
public void startDocument() throws SAXException {
		
}
public void startElement(String uri, String localName, String qName, Attributes attributes)
				throws SAXException {
if("student".equals(qName)){
student  = new Student();
}
if("name".equals(qName)){
student.setNameType(attributes.getValue("type"));
}
//赋值标签名称【student.id.name.属性】
tag = qName;
}
public void  endElement(String uri, String localName, String qName) throws 	   SAXException {
if(studentList != null && studentList.size()>2){
//增加效率,避免内存占取过大,按条数添加数据
insertStudentList(studentList);
//清除数据
studentList.clear();
}
tag = ""; //标签置空
}
public void endDocument() throws SAXException {
//标签处理完成处理未完成数据
if(studentList  != null && studentList .size()>0){
insertStudentList(studentList);
}
//清除数据
studentList.clear();
}
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
// 这里是内容,但是,无法直接判断属于哪一个元素。
String string = new String(ch, start, length);
//处理标签属性
if("id".equals(tag)){
student.setId(string);
}
if("name".equals(tag)){
student.setName(string);
}

}
}

3.事务控制下,批量插入数据(Mysql和Oracle批量插入不一样,详情可以查阅一下其他文档)

@Transactional
public void insertStudentList(List<Student> studentList){
studentMapper.insertStudentList(studentList);
}
至此数据处理完毕。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KeepMoving00

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值