我一直在想如何读取XML文件,但在回答之前,请先阅读整篇文章。
例如,我有以下内容:
<?xml version="1.0" encoding="UTF-8"?>
<messages>
<incoming id="0" class="HelloIlikeyou" />
</messages>
我想要的是从标签中获取所有的值。我想把它放在一个字典里,其中键为"incoming/outgoing",然后它将包含一对Pair列表作为值,其中键为id值,值为class值。
所以我得到了这个:
HashMap<String, List<Pair<Integer, String>>> headers = new HashMap<>();
然后它会存储这个:
HashMap.get("incoming").add(new Pair<>("0", "HelloIlikeyou"));
但我不知道该如何做,虽然我已经有了一部分,但它还没有起作用:
File xml = new File(file);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xml);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("messages");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
System.out.println("Type: " + node.getNodeValue() + " packet ID " + node.getUserData("id"));
}