Parse XML With DocumentBuilder

Parse an XML payload into a DOM tree with a hardened DocumentBuilderFactory that rejects DOCTYPE declarations, then read elements and attributes.

JavaData Fetching

Code

snippet
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

import javax.xml.parsers.DocumentBuilderFactory;

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

public class XmlConfigReader {

    public static void main(String[] args) throws Exception {
        String xml = """
                <deploy>
                  <service name="api" replicas="3" />
                  <service name="worker" replicas="2" />
                </deploy>""";

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // 加固:禁用 DOCTYPE 声明,堵住 XXE 外部实体注入
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

        Document doc = factory.newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));

        NodeList services = doc.getElementsByTagName("service");
        for (int i = 0; i < services.getLength(); i++) {
            Element service = (Element) services.item(i);
            System.out.println(service.getAttribute("name")
                    + " replicas=" + service.getAttribute("replicas"));
        }
        System.out.println("root: " + doc.getDocumentElement().getTagName());
    }
}

How it works

Structurally, expect the class XmlConfigReader and nothing else.

The one repetition in this snippet is the loop for (int i = 0; i < services.getLength(); i++).

What to watch for

  • Plan for an install step: org.w3c.dom.Document, org.w3c.dom.Element and org.w3c.dom.NodeList are a real dependency, resolved by the package manager.

Using it

Running the file prints labeled results such as root: — each operation’s effect is visible in the output.

Key statements

factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `org.w3c.dom.Document`, `org.w3c.dom.Element` and `org.w3c.dom.NodeList`, which the package manager must provide.