今更、org.xml.sax.helpers.DefaultHandler , SAXParser のサンプルを書きなおした。
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* XmlHandler
*/
public abstract class XmlHandler extends DefaultHandler{
private Stack<String> pathStack;
private Map<String,String> bmap;
private Map<String,Map<String,String>> attrmap;
/**
* タグ読込完了
* @param qName タグ名
* @param xpath xmlフルパス
* @param attributes 属性key="value"をMap変換後
* @param body tag body
*/
public abstract void onReadedTag(String qName,String xpath,Map<String,String> attributes,String body);
@Override
public void startDocument() throws SAXException{
pathStack = new Stack<String>();
bmap = new HashMap<String,String>();
attrmap = new HashMap<String,Map<String,String>>();
}
@Override
public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException{
pathStack.push(qName);
Map<String,String> amap = new HashMap<String,String>();
for(int i=0;i < attributes.getLength();i++){
amap.put(attributes.getQName(i),attributes.getValue(i));
}
attrmap.put(getXPath(),amap);
}
@Override
public void characters(char[] ch,int start,int length) throws SAXException{
String path = getXPath();
if (bmap.containsKey(path)){
bmap.put(path,bmap.get(path)+(new String(ch,start,length).trim()));
}else{
bmap.put(path,(new String(ch,start,length).trim()));
}
}
@Override
public void endElement(String uri,String localName,String qName) throws SAXException{
String path = getXPath();
onReadedTag(qName,path,attrmap.get(path),bmap.get(path));
attrmap.remove(path);
bmap.remove(path);
pathStack.pop();
}
@Override
public void endDocument() throws SAXException{
bmap.clear();
attrmap.clear();
pathStack.clear();
}
private String getXPath(){
StringBuffer sb = new StringBuffer();
for(String s : pathStack){
sb.append("/"+s);
}
return sb.toString();
}
}
------------------------------------------
使い方のサンプル例は、、
XmlHandler handler = new XmlHandler(){
@Override
public void onReadedTag(String qName,String xpath,Map<String,String> attributemap,String body){
System.out.println(qName+" "+xpath);
for(String key : attributemap.keySet()){
System.out.println("Attributes : "+key+" = "+attributemap.get(key));
}
System.out.println("["+body+"]");
}
};
SAXParserFactory saxparserFactory = SAXParserFactory.newInstance();
saxparserFactory.setNamespaceAware(true);
SAXParser saxParser = saxparserFactory.newSAXParser();
saxParser.parse(new FileInputStream(new File(url.toURI())),handler);