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);
}
至此数据处理完毕。