LoginSignup
1
1

More than 5 years have passed since last update.

[XML] 空要素の属性でMapをつくる方法

Last updated at Posted at 2014-11-09

やりたいこと

下記のような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というライブラリを使っているのでこれを使ってもっとさくっと簡単に同じようなことをやりたいのだけどわからない。うーん。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1