解析XML
方式一:
方式二:
方式三:
方式N:
好可爱的demo:
document.xml文件内容如下: <?xml version="1.0" encoding="UTF-8"?> <node> <key1> value1</ key1> < key2> value 2</ key2> < key3> value 3</ key3> </node>
public class ParseXml { public static Map<String, String> parseFile(String filePath) { File file = new File(filePath); if (!file.exists()) { return null; } try { Map<String, String> map = new HashMap<String, String>(); //解析方式不限 SAXReader reader = new SAXReader(); Document document = reader.read(file); Node node = document.selectSingleNode("node/key1"); map.put("key1", node.getText()); node = document.selectSingleNode("node/key2"); map.put("key2", node.getText()); node = document.selectSingleNode("node/key3"); map.put("key", node.getText()); return map; } catch (Exception e) { System.err.println("解析文件异常"); e.printStackTrace(); return null; } } public static void main(String[] args) { Map<String, String> resultMap = parseFile("D:/document.xml"); } }