Java HTML / XML How to - Parse xml using DOM API








Question

We would like to know how to parse xml using DOM API.

Answer

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
//from ww w.  j  a  v  a 2  s . c  o m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {
    public static void main(String[] args) throws Exception {
        InputSource source = new InputSource(new StringReader("<root>\n" +
                                                            "<field name='firstname'>\n" +
                                                            "    <value>John</value>\n" +
                                                            "</field>\n" +
                                                            "<field name='lastname'>\n" +
                                                            "    <value>Citizen</value>\n" +
                                                            "</field>\n" +
                                                            "<field name='DoB'>\n" +
                                                            "    <value>01/01/1980</value>\n" +
                                                            "</field>\n" +
                                                            "<field name='Profession'>\n" +
                                                            "    <value>Manager</value>\n" +
                                                            "</field>\n" +
                                                            "</root>" ));

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        Document document = documentBuilder.parse(source);

        NodeList allFields = (NodeList) document.getElementsByTagName("field");

        Map<String, String> data = new HashMap<>();
        for(int i = 0; i < allFields.getLength(); i++) {
            Element field = (Element)allFields.item(i);
            String nameAttribute = field.getAttribute("name");
            Element child = (Element)field.getElementsByTagName("value").item(0);
            String value = child.getTextContent();
            data.put(nameAttribute, value);
        }

        for(Map.Entry field : data.entrySet()) {
            System.out.println(field.getKey() + ": " + field.getValue());
        }
    }
}