【20140416】【Java】SAXを使ってXMLの出現要素数を調べる
お題
プログラム概要
XMLの要素の出現件数をMAPに格納しておき、
最後に要素ごとの出現件数を表示する
ソース
SAXSampleMain
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import java.util.*;
public class SAXSampleMain {
public static void main(String[] args) {
// SAXを準備する
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
// ハンドラを準備する
Handelr1 h1 = new Handelr1();
// 文書を読み込む
sp.parse(new FileInputStream("sample.xml"), h1);
// 各エレメントの数を表示
System.out.println("");
System.out.println("Summary=========");
for(Map.Entry<String, Integer> e : h1.map.entrySet()) {
System.out.println(e.getKey() + " : " + e.getValue());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
System.exit(1);
} catch (SAXException e) {
e.printStackTrace();
System.exit(1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
Handelr1
import java.util.HashMap;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
// ハンドラクラス
public class Handelr1 extends DefaultHandler {
public HashMap<String, Integer> map = new HashMap<String, Integer>();
// 文書の開始
public void startDocument() {
System.out.println("Start document");
}
// 文書の終了
public void endDocument() {
System.out.println("End document");
}
// 要素の開始
public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) {
System.out.println(" Start " + qName);
if(map.containsKey(qName)) {
Integer cnt = map.get(qName);
cnt++;
map.put(qName, cnt);
} else {
map.put(qName, 1);
}
}
// 要素の終了
public void endElement(String namespaceURI, String localName, String qName) {
System.out.println(" End " + qName);
}
// 要素内のテキストを表示
public void characters(char[] ch, int start, int length) {
String str = new String(ch, start, length);
System.out.println(" " + str);
}
}
sample.xml
<hoge> <piyo>PIYOTEXT</piyo> <foo></foo> <bar>BARTEXT</bar> <foo></foo> </hoge>
実行結果
Start document Start hoge Start piyo PIYOTEXT End piyo Start foo End foo Start bar BARTEXT End bar Start foo End foo End hoge End document Summary========= hoge : 1 foo : 2 bar : 1 piyo : 1