Parsing XML file with DOM

There are ways in Java how you can read or write  XML files.  Here is a way of reading and writing a XML file using DOM.

The function readXML() reads the specified file.  It does all the preliminary works for reading an XML file.  It creates DocumentBuilderFactory, DocumentBuilder, and Document.  The XML file will be read by calling DocumentBuilder#parse().

The parseXMLTree() function recursively parses the DOM tree.  It outputs the text contents of each <value> tag of the node.  A word of caution: it is not Node#getNodeValue() that retrieves the text content of the node.  Call Node#getTextContent() instead.

The function writeXML() does all the work for writing out the XML.  It creates TransformerFactor, Transformer, and DOMSource.  The StreamResult object creates the stream for the specified file.  Finally, call Transformer#transform() and it will write out the XML.
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

    public void readXML(String xmlFile) {
        try {
            File inputFile = new File(xmlFile);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();
            parseXMLTree(doc.getDocumentElement(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseXMLTree(Node node, int level) {
        if (node.getNodeName().equals("value")) {
            for (int i = 0; i < level - 1; i++) {
                System.out.print("-");
            }
            System.out.println(node.getTextContent());
        } else {

            NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                parseXMLTree(nodeList.item(i), level + 1);
            }
        }
    }

    public void writeXML(String xmlFile) {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(xmlFile));
            transformer.transform(source, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Comments

Popular posts from this blog

Logging your Maven project with Logback

TreeEditor: Customizing Drag and Drop

Spring Tool Suite