やりたいこと
下記のようなxmlをパースしてMapを作りたい。
<?xml version="1.0" encoding="utf-8"?>
<config>
<map name="aaa">
<entry key="1" value="a"/>
<entry key="2" value="b"/>
<entry key="3" value="c"/>
<entry key="4" value="d"/>
<entry key="5" value="e"/>
</map>
<map name="bbb">
<entry key="1" value="ee"/>
<entry key="2" value="ff"/>
<entry key="3" value="gg"/>
<entry key="4" value="hh"/>
</map>
<map name="ccc">
<entry key="1" value="iii"/>
<entry key="2" value="jjj"/>
<entry key="3" value="kkk"/>
<entry key="4" value="lll"/>
</map>
</config>
やってみたこと
XPathを使う。
public class Main {
public static void main(String[] args) throws Exception {
File f = new File("./res/sample.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/config/map[@name=\"aaa\"]/entry");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
Element element = (Element) nl.item(i);
System.out.println(element.getAttribute("key") + ":" + element.getAttribute("value"));
// Mapを用意しておいて値をセットしていけばいい。
}
}
}
参考: How to get specific XML elements with specific attribute value?
Simpleを使う。
Simpleというライブラリを使っているのでこれを使ってもっとさくっと簡単に同じようなことをやりたいのだけどわからない。うーん。