Java从xml读取键值对

时间:2015-08-14 16:54:33

标签: java

我是java的新手,我想提供的密钥是" aaa"并获得价值" bbb"从下面的xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <General>
    <add key="aaa" value="bbb"/>
  </General>
</configuration>

这是我的代码无效:

           Properties prop = new Properties();
            InputStream is = new FileInputStream("c:\\propFileName.config");
            prop.load(is);
            String result = prop.getProperty("aaa");

请帮忙!

1 个答案:

答案 0 :(得分:2)

将此用于此类xml文件:

try {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("E:\\temp\\dist\\filename.config");

    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("//configuration/General/add[@key]");
    NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

    for (int c = 0; c < nl.getLength(); c++) {
        Node currentItem = nl.item(c);
        String key = currentItem.getAttributes().getNamedItem("key").getNodeValue();
        String value = currentItem.getAttributes().getNamedItem("value").getNodeValue();
        urlList.put(key, value);
    }
} catch (Exception e) {
    e.printStackTrace();
}