user2528595 user2528595 - 3 months ago 28
Java Question

Java XML Reading

I've been wondering how to read XML files, but before you answer, read the whole post.

For example I have:

<?xml version="1.0" encoding="UTF-8"?>

<messages>

<incoming id="0" class="HelloIlikeyou" />

</messages>


What I want, is get all values from the tag . I want to place it in a dictionary, which key is incoming/outgoing, and then it will contain a list of Pair as value, with as key the id value and as value the class value.

So I got this:

HashMap<String, List<Pair<Integer, String>>> headers = new HashMap<>();


Then it will store this:

HashMap.get("incoming").add(new Pair<>("0", "HelloIlikeyou"));


But I don't know how to do it, I already got a part but it aint working:

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"));
}

Answer

This is what you want:

    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"));
    }
    }
}
}

This gives me the following output:

Type: incoming packet ID id="0" - class: class="HelloIlikeyou"