Sax解析实现查询
新建一个SaxParseXml类继承DefaultHandler
public class SaxParseXml extends DefaultHandler {}
代码
package com.bosssoft.hr.train.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @作者 吴志鸿
* @maven 3.6.3
* @jdk 1.8
*/
public class SaxParseXml extends DefaultHandler {
private HashMap<String,String> map = null;
private List<HashMap<String,String>> list = null;
private String currentTag = null;
private String currentValue = null;
private String nodeName = null;
public SaxParseXml(String nodeName){
this.nodeName = nodeName;
}
public List<HashMap<String,String>> getList(){
return list;
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if(qName.equals(nodeName)){
list.add(map);
map = null;
}
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
list = new ArrayList();
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
if(currentTag != null && map != null){
currentValue = new String(ch,start,length);
if(currentValue!=null&&!currentValue.trim().equals("")&&!currentValue.trim().equals("
")){
map.put(currentTag,currentValue);
}
}
currentTag = null;
currentValue = null;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(qName.equals(nodeName)){
map = new HashMap<String, String>();
if(attributes != null && map != null){
for(int i=0; i<attributes.getLength(); i++){
map.put(attributes.getQName(i),attributes.getValue(i));
}
}
}
currentTag = qName;
}
//查询全部用户
public static void queryall() throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory saxParserFactor = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactor.newSAXParser();
SaxParseXml item = new SaxParseXml("student");
saxParser.parse("src/com/bosssoft/hr/train/xml/student.xml",item);
List<HashMap<String, String>> list1 = item.getList();
for (HashMap<String, String> p : list1) {
System.out.println(p.toString());
}
}
}