Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java XML Reading

Tags:

java

xml

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"));    
            }
like image 513
user2528595 Avatar asked Jun 07 '26 23:06

user2528595


1 Answers

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

like image 158
Alks Avatar answered Jun 09 '26 13:06

Alks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!