3

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"));    
            }
3
  • 1
    What do you mean "it aint working" (sic)? Getting exceptions? Not returning any data? Computer catches on fire? Commented Jun 27, 2013 at 14:57
  • You are still operating on the messages node, you have to iterate over node.getChildNodes() Commented Jun 27, 2013 at 15:07
  • could anyone answer this? [enter link description here][1] [1]: stackoverflow.com/questions/24757825/… Commented Jul 15, 2014 at 12:09

4 Answers 4

3

You can use JAXB, i think that is the best way. take a look of this: Jaxb tutorial

Sign up to request clarification or add additional context in comments.

2 Comments

JAXB, imo, provides the worst api among all xml serialization libs. XStream is far superior in api fluency and convenience. The reason behind it might be JAXB is a ref implementation and can't use exotic stuff like XStream.
Please provide a compelling reason for using this particular tool rather than just suggesting it.
2

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"

1 Comment

Thanks, but I had to add: if (attributes == null) { continue; } To prevent null errors (my project works on a way it will stop after a bug and because that was a null bug I got an error). Thanks anyway for this fix.
0
Node node = nodes.item(i);
if (node instanceOf Element) {
    Element elem = (Element)node;
    String id = elem.getAttribute("id");
    ...

So you were almost there. The W3C classes are a bit old-stylish.

Comments

0

Use one of the many available libraries that will do that for you, for example XStream:

http://x-stream.github.io/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.