Java XML读取

3

我一直在想如何读取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"));    
            }

1
你说的“它不工作”是什么意思?是出现了异常吗?还是没有返回任何数据?还是电脑着火了? - James Cronen
你仍在操作 messages 节点,你需要迭代 node.getChildNodes()。 - Manuel Manhart
有人可以回答这个问题吗?点击此处 - Sharmishtha Kulkarni
4个回答

3
您可以使用JAXB,我认为这是最好的方法。参考以下链接: Jaxb教程

JAXB,我认为在所有XML序列化库中提供的API最差。相比之下,XStream在API流畅性和便利性方面要优秀得多。这背后的原因可能是JAXB是一个参考实现,不能使用像XStream这样的奇特东西。 - Nikola Yovchev
请提供使用此特定工具的充分理由,而不仅仅是建议它。 - Mgetz

2
这是您想要的内容:
    public static void main(final String[] args)
    throws ParserConfigurationException, SAXException, IOException {
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);
    for (int j = 0; j < node.getChildNodes().getLength(); j++) {

    Node child = node.getChildNodes().item(j);

    if (!child.getNodeName().equals("#text")) {
        NamedNodeMap attributes = child.getAttributes();

        System.out.println("Type: " + child.getNodeName()
            + " packet ID " + attributes.getNamedItem("id")
            + " - class: " + attributes.getNamedItem("class"));
    }
    }
}
}

这使我得到以下输出:
Type: incoming packet ID id="0" - class: class="HelloIlikeyou"

谢谢,但我不得不添加:if (attributes == null) { continue; }以防止空指针错误(我的项目在出现错误后会停止运行,因为这是一个空指针错误,所以我得到了一个错误)。无论如何,还是感谢您的修复。 - user2528595

0

0
Node node = nodes.item(i);
if (node instanceOf Element) {
    Element elem = (Element)node;
    String id = elem.getAttribute("id");
    ...

所以你差不多到了那里。W3C的类有点老式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接