Validating XML with Document Type Definitions (DTDs)
Describe and check XML structure with a DTD: internal and external DOCTYPE declarations, element content rules, #PCDATA and mixed content, ATTLIST types and defaults, ID and IDREF, entities, validating DOM parsers that drop whitespace, error handlers, and XML catalogs.
kvi5hnuCode Sprout team member11 min readOn this page
Article 40 showed how tedious it is to read a DOM tree defensively. You skip whitespace nodes, check every tag name, and check that each expected child is present, in the right order. Much of that checking can be handed to the parser. You describe the allowed structure once, and a validating parser checks every document against it. If a document passes, your code can rely on its shape.
There are two common ways to write that description: the document type definition (DTD), which is part of the XML 1.0 standard itself, and XML Schema, a richer language covered in the next article. A DTD rule such as
<!ELEMENT font (name,size)>
says that a font element always contains exactly a name followed by a size.
Attaching a DTD
A DTD is attached through the DOCTYPE declaration in the prolog. Its first word must be the name of the root element. The rules can be written inline, in the internal subset between brackets:
<?xml version="1.0"?>
<!DOCTYPE config [
<!ELEMENT config (entry)*>
...
]>
<config>...</config>
More often, they live in a separate file, named by a system identifier (a relative or absolute URI):
<!DOCTYPE config SYSTEM "config.dtd">
<!DOCTYPE config SYSTEM "https://example.com/dtds/config.dtd">
A relative identifier is resolved against the document's own location. So parse from a File or URI, not from a bare InputStream, or give the InputSource a system id.
Widely used DTDs also have a public identifier, a name inherited from SGML, followed by a system identifier as a fallback:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
A processor that already has a copy of the DTD for that public identifier doesn't need to fetch the URL.
Element rules
<!ELEMENT name content> declares an element and what it may contain. The content model is a small regular expression over child element names:
| Content | Meaning |
|---|---|
E*, E+, E? | zero or more, one or more, zero or one E |
(E1, E2, ..., En) | E1 followed by E2 ... followed by En |
(E1 | E2 | ... | En) | one of the alternatives |
(#PCDATA) | text only |
(#PCDATA | E1 | ... | En)* | mixed content: text and the listed elements in any order and number |
EMPTY | no content at all |
ANY | anything (no checking) |
Some examples:
<!ELEMENT menu (item)*>
<!ELEMENT font (name,size)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT chapter (intro,(heading,(para|image|table|note)+)+)>
The last rule says that a chapter starts with an intro, followed by one or more sections, each made of a heading and one or more paragraphs, images, tables or notes.
#PCDATA stands for "parsed character data": text in which the parser still looks for < and &. Text can appear in only two forms. Either an element holds only text, (#PCDATA), or it has mixed content, (#PCDATA|em|strong)*, where the children can't be ordered or counted. A rule like (image, #PCDATA) is illegal. That's another reason to keep data formats free of mixed content: introduce a caption element instead.
Content models must also be deterministic. The parser must always know which part of the rule the next child belongs to without looking further ahead. ((x,y)|(x,z)) breaks this rule, because after seeing x the parser can't tell which branch it's in. Rewrite it as (x,(y|z)). Some ambiguous models, like ((x,y)*|x?), can't be rewritten at all. The JDK's parser doesn't enforce this rule: it accepts documents matching an ambiguous model, such as both <x/><y/> and <x/><z/> for ((x,y)|(x,z)). Other validators may reject the DTD itself, so write deterministic models anyway for portability.
Attribute rules
<!ATTLIST element attribute type default> declares attributes. Several attributes can be declared in one ATTLIST.
| Type | Values |
|---|---|
CDATA | any string |
(v1|v2|...|vn) | one of the listed values (an enumeration) |
NMTOKEN, NMTOKENS | a name token, or a whitespace-separated list of them |
ID | a name that must be unique in the document |
IDREF, IDREFS | a reference to an existing ID, or a list of them |
ENTITY, ENTITIES | a reference to an unparsed external entity (an SGML leftover, rarely used) |
| Default | Meaning |
|---|---|
#REQUIRED | the attribute must be present |
#IMPLIED | it's optional, with no default |
"value" | it's optional, and the parser reports value when it's absent |
#FIXED "value" | if present, it must be value; the parser always reports value |
<!ATTLIST font style (plain|bold|italic|bold-italic) "plain">
<!ATTLIST size unit CDATA #IMPLIED>
<!ATTLIST entry id ID #REQUIRED like IDREF #IMPLIED>
The parser normalizes attribute values. It replaces character and entity references and turns line breaks and tabs into spaces. For all types except CDATA, it also strips leading and trailing spaces and collapses inner runs of spaces. (CDATA as an attribute type has nothing to do with <![CDATA[...]]> sections.)
Article 39 recommended elements over attributes for data. Enumerated attributes are the exception where attributes shine: the parser checks the value and supplies a default.
ID and IDREF give documents cross-references that the parser checks: every ID must be unique, and every IDREF must point to an existing ID. In the DOM, Document.getElementById finds an element by its ID-typed attribute. Without a DTD or schema the parser doesn't know which attribute is the ID, so getElementById returns null.
Entities
A DTD can also declare general entities, named pieces of text that the parser substitutes wherever &name; appears:
<!ENTITY company "Example Fonts & Co.">
Entities were once a common way to keep translatable strings out of documents. External entities (SYSTEM "file") pull in other files. That's the feature article 40 warned about. Parameter entities (<!ENTITY % name ...>, used as %name;) work inside DTDs themselves, for reuse across declarations.
Turning on validation
DTD validation is a factory setting:
var factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
The biggest everyday benefit is the second line. Once the DTD says that font contains (name,size), the parser knows that whitespace between those children is mere formatting and can drop it. The font element then has exactly two children, and code like
var name = (Element) font.getChildNodes().item(0);
var size = (Element) font.getChildNodes().item(1);
is correct without any further checks.
Validation errors are reported to the ErrorHandler's error method, and they don't stop parsing. The default handler only prints a warning to standard error and lets parse return normally! Always install your own error handler when validating, and decide what to do with errors: collect them, log them, or throw from error to abandon the document. Violations of well-formedness still go to fatalError and end parsing.
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException e) { log(e); }
public void error(SAXParseException e) throws SAXException { throw e; } // invalid: give up
public void fatalError(SAXParseException e) throws SAXException { throw e; }
});
Resolving DTDs locally
An EntityResolver intercepts every external reference. Its resolveEntity(publicId, systemId) method returns an InputSource with the content, or null to let the parser fetch the system identifier itself:
builder.setEntityResolver((publicId, systemId) ->
"-//Example//DTD Config 1.0//EN".equals(publicId)
? new InputSource(Solution.class.getResourceAsStream("/config.dtd"))
: null);
Instead of hard-coding such mappings, you can use XML catalogs, an OASIS standard supported by the javax.xml.catalog API since Java 9 (JEP 268). A catalog file maps public and system identifiers to local URIs:
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="public">
<public publicId="-//Example//DTD Config 1.0//EN" uri="config.dtd"/>
<system systemId="https://example.com/dtds/config.dtd" uri="config.dtd"/>
</catalog>
Relative uri values are resolved against the catalog file's location. Install a resolver built from one or more catalog files:
builder.setEntityResolver(CatalogManager.catalogResolver(
CatalogFeatures.defaults(), Path.of("catalog.xml").toAbsolutePath().toUri()));
The resulting CatalogResolver also implements the resolver interfaces of StAX, schema validation and XSLT. You can also leave the code alone and set the catalog files with the javax.xml.catalog.files system property (a semicolon-separated list of URIs) together with javax.xml.useCatalog. Since JDK 22 the JDK also has a built-in catalog for the W3C's own DTDs, such as XHTML. The jdk.xml.jdkcatalog.resolve property (continue, ignore or strict) decides what happens to references that no catalog resolves.
The program
The demo writes a DTD and some documents to a temporary directory. The valid document shows the dropped whitespace, an attribute default, an expanded entity and getElementById. The invalid document triggers a list of errors that a collecting error handler gathers. Finally, a document that refers to an unreachable URL is parsed through a catalog, and once more through a hand-written entity resolver.
import java.io.*;
import java.nio.file.*;
import java.util.*;
import javax.xml.catalog.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class Solution {
static final String DTD = """
<!ELEMENT config (entry)*>
<!ELEMENT entry (font|color)>
<!ATTLIST entry id ID #REQUIRED
like IDREF #IMPLIED>
<!ELEMENT font (name,size)>
<!ATTLIST font style (plain|bold|italic|bold-italic) "plain">
<!ELEMENT name (#PCDATA)>
<!ELEMENT size (#PCDATA)>
<!ATTLIST size unit CDATA #IMPLIED>
<!ELEMENT color (red,green,blue)>
<!ELEMENT red (#PCDATA)>
<!ELEMENT green (#PCDATA)>
<!ELEMENT blue (#PCDATA)>
<!ENTITY company "Example Fonts & Co.">
""";
/** Collects validation errors instead of printing them. */
static class Collector implements ErrorHandler {
final List<String> messages = new ArrayList<>();
public void warning(SAXParseException e) { messages.add("warning: " + e.getMessage()); }
public void error(SAXParseException e) { messages.add("line " + e.getLineNumber() + ": " + e.getMessage()); }
public void fatalError(SAXParseException e) throws SAXException { throw e; }
}
static DocumentBuilderFactory validating() {
var factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
return factory;
}
static void validate(String label, Path file) throws Exception {
DocumentBuilder builder = validating().newDocumentBuilder();
var errors = new Collector();
builder.setErrorHandler(errors);
builder.parse(file.toFile());
System.out.println(label + ": " + (errors.messages.isEmpty() ? "valid" : String.join("\n ", errors.messages)));
}
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("dtd");
try {
Files.writeString(dir.resolve("config.dtd"), DTD);
Path good = dir.resolve("good.xml");
Files.writeString(good, """
<?xml version="1.0"?>
<!DOCTYPE config SYSTEM "config.dtd">
<config>
<entry id="title">
<font>
<name>Helvetica</name>
<size unit="pt">36</size>
</font>
</entry>
<entry id="body" like="title">
<font style="bold"><name>&company;</name><size>12</size></font>
</entry>
</config>""");
System.out.println("--- whitespace and defaults ---");
DocumentBuilder builder = validating().newDocumentBuilder();
builder.setErrorHandler(new Collector());
Document doc = builder.parse(good.toFile());
Element font = (Element) doc.getElementsByTagName("font").item(0);
NodeList children = font.getChildNodes();
System.out.println("font children: " + children.getLength()
+ " -> " + children.item(0).getNodeName() + ", " + children.item(1).getNodeName());
var name = (Element) children.item(0);
var size = (Element) children.item(1);
System.out.println("name=" + name.getTextContent() + ", size=" + Integer.parseInt(size.getTextContent())
+ ", style (defaulted)=" + font.getAttribute("style")
+ ", specified=" + font.getAttributeNode("style").getSpecified());
System.out.println("entity expanded: " + doc.getElementsByTagName("name").item(1).getTextContent());
System.out.println("getElementById(\"body\"): " + doc.getElementById("body").getAttribute("like"));
System.out.println("doctype: name=" + doc.getDoctype().getName() + ", systemId=" + doc.getDoctype().getSystemId());
var plain = DocumentBuilderFactory.newInstance().newDocumentBuilder();
System.out.println("without validation: font has "
+ ((Element) plain.parse(good.toFile()).getElementsByTagName("font").item(0)).getChildNodes().getLength()
+ " children");
System.out.println("--- validation errors ---");
validate("good.xml", good);
Path bad = dir.resolve("bad.xml");
Files.writeString(bad, """
<?xml version="1.0"?>
<!DOCTYPE config SYSTEM "config.dtd">
<config>
<entry id="a"><font style="slanted"><size>1</size><name>x</name></font></entry>
<entry id="a"><color><red>0</red><green>0</green></color></entry>
<entry like="nowhere"><font><name>y</name><size>2</size><extra/></font></entry>
</config>""");
validate("bad.xml", bad);
System.out.println("--- public identifiers and catalogs ---");
Path remote = dir.resolve("doc.xml");
Files.writeString(remote, """
<?xml version="1.0"?>
<!DOCTYPE config PUBLIC "-//Example//DTD Config 1.0//EN" "https://example.invalid/config.dtd">
<config><entry id="x"><color><red>1</red><green>2</green><blue>3</blue></color></entry></config>""");
Path catalog = dir.resolve("catalog.xml");
Files.writeString(catalog, """
<?xml version="1.0"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="public">
<public publicId="-//Example//DTD Config 1.0//EN" uri="config.dtd"/>
</catalog>""");
DocumentBuilder withCatalog = validating().newDocumentBuilder();
var errors = new Collector();
withCatalog.setErrorHandler(errors);
withCatalog.setEntityResolver(CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalog.toUri()));
Document d = withCatalog.parse(remote.toFile());
System.out.println("resolved from the catalog: valid=" + errors.messages.isEmpty()
+ ", blue=" + d.getElementsByTagName("blue").item(0).getTextContent());
DocumentBuilder custom = validating().newDocumentBuilder();
custom.setErrorHandler(new Collector());
custom.setEntityResolver((publicId, systemId) -> {
System.out.println("resolveEntity(" + publicId + ", " + systemId + ")");
return new InputSource(new StringReader(DTD));
});
custom.parse(remote.toFile());
} finally {
try (var files = Files.list(dir)) {
for (Path p : files.toList()) Files.delete(p);
}
Files.delete(dir);
}
}
}
--- whitespace and defaults ---
font children: 2 -> name, size
name=Helvetica, size=36, style (defaulted)=plain, specified=false
entity expanded: Example Fonts & Co.
getElementById("body"): title
doctype: name=config, systemId=config.dtd
without validation: font has 5 children
--- validation errors ---
good.xml: valid
bad.xml: line 4: Attribute "style" with value "slanted" must have a value from the list "plain bold italic bold-italic ".
line 4: The content of element type "font" must match "(name,size)".
line 5: Attribute value "a" of type ID must be unique within the document.
line 5: The content of element type "color" is incomplete, it must match "(red,green,blue)".
line 6: Attribute "id" is required and must be specified for element type "entry".
line 6: Element type "extra" must be declared.
line 6: The content of element type "font" must match "(name,size)".
line 7: An element with the identifier "nowhere" must appear in the document.
--- public identifiers and catalogs ---
resolved from the catalog: valid=true, blue=3
resolveEntity(-//Example//DTD Config 1.0//EN, https://example.invalid/config.dtd)
The .invalid domain is reserved and never resolves, so if either resolver failed, the program would have reported an error. Note that the attribute style reports getSpecified() == false: its value came from the DTD default, not from the document.
Common questions
DTD or XML Schema: which should I use today? XML Schema for new formats: it has data types (integers, dates, patterns), namespaces support, and better tools. DTDs remain in older standards and in documents that use entities, and they are still the only way to declare entities. Many formats offer both.
My parser hangs or fails because it tries to download a DTD. How do I stop that?
Even a non-validating parser reads an external DTD, because it may define entities and attribute defaults. Map the DTD to a local copy with a catalog or entity resolver, or, if you don't need it, turn loading off: factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false).
Can I validate a document against a DTD it does not reference?
Not directly; DTD validation follows the DOCTYPE in the document. You can intercept the reference with an entity resolver that returns your DTD, but for documents without a DOCTYPE, schema validation with an explicitly chosen schema (next article) is the clean solution.
If a document parses without errors, is it valid?
Only if validation was enabled and your error handler treats error calls as failures. A plain parse checks well-formedness only.
Why does getElementById return null?
The parser does not know which attribute is an ID unless a DTD or schema declares it with type ID. An attribute that is merely named id does not count. With a schema, or after building a tree yourself, setIdAttribute can mark it.
API reference
| API | Purpose |
|---|---|
DocumentBuilderFactory.setValidating(true) | validate against the document's DTD |
setIgnoringElementContentWhitespace(true) | drop whitespace in element-only content (needs validation) |
DocumentBuilder.setErrorHandler(handler) | receive warning, error and fatalError callbacks |
ErrorHandler.error(SAXParseException) | called for validity errors; parsing continues unless you throw |
DocumentBuilder.setEntityResolver(resolver) | supply external DTDs and entities yourself |
EntityResolver.resolveEntity(publicId, systemId) | return an InputSource, or null for default handling |
CatalogManager.catalogResolver(features, uris...) | resolver driven by catalog files (Java 9) |
CatalogFeatures.defaults() | default catalog settings |
Document.getDoctype() | the DocumentType with getName, getPublicId, getSystemId |
Document.getElementById(id) | element with the given ID attribute value |
Attr.getSpecified() | whether an attribute was in the document or came from a default |
Summary
- A DTD declares the allowed elements, their content models, their attributes and entities. Attach it with
<!DOCTYPE root SYSTEM "uri">, aPUBLICidentifier, or an internal subset. - Content models use
,for sequence,|for choice, and* + ?for repetition. Text is either(#PCDATA)alone or unordered mixed content, and models must be deterministic. ATTLISTgives attributes types (CDATA, enumerations,ID,IDREF,NMTOKEN) and defaults (#REQUIRED,#IMPLIED, a value,#FIXED).- With
setValidating(true)andsetIgnoringElementContentWhitespace(true), a validated tree has no formatting whitespace in element-only content. - Validity errors don't stop parsing by themselves. Install an
ErrorHandlerand act onerror. - Resolve DTDs locally with an
EntityResolveror an XML catalog, never by downloading them on each parse.
Practice Questions
Write a DTD rule for a contact element that has a name, then either an email or a phone, then any number of note elements.
<!ELEMENT contact (name, (email|phone), note*)>, plus declarations for the child elements, such as <!ELEMENT name (#PCDATA)>.
Why is \<!ELEMENT figure (image, #PCDATA)\> illegal, and how would you fix the design?
#PCDATA may appear only alone, (#PCDATA), or at the start of an unordered mixed-content group, (#PCDATA|image)*. A fixed position for text after an element can't be expressed. Introduce a text-only element: <!ELEMENT figure (image, caption)> with <!ELEMENT caption (#PCDATA)>.
A validating parser reports errors but parse still returns a Document. Why, and how do you make invalid documents fail?
Validity errors go to ErrorHandler.error, which by default just reports them. Only well-formedness errors are fatal. Install an ErrorHandler whose error method throws the SAXParseException, or collects errors that you check after parsing.
What does \<!ATTLIST font style (plain|bold) "plain"\> give you that \<!ATTLIST font style CDATA #IMPLIED\> doesn't?
The parser rejects any value other than plain or bold, and when the attribute is absent it reports plain, so getAttribute("style") never returns an empty string. With CDATA #IMPLIED, any value is accepted and a missing attribute yields "".
Your application parses XHTML files and has become very slow. What is a likely cause, and what are two fixes?
The documents refer to the W3C XHTML DTD by URL, and the parser downloads it, slowly and often throttled, for every file. Fix it with an EntityResolver or XML catalog that maps the public identifier to a local copy (recent JDKs also include a built-in catalog for these DTDs), or, if you don't need the DTD at all, disable external DTD loading with the feature http://apache.org/xml/features/nonvalidating/load-external-dtd set to false on a non-validating parser. (Setting ACCESS_EXTERNAL_DTD to "" does not skip the DTD: it makes such documents fail to parse.)
Previous: Parsing XML with DOM: DocumentBuilder, Nodes and Secure Parsing
Next: Validating XML with XML Schema: Types, Sequences and a Practical Example
Related reading
- Parsing XML with DOM: DocumentBuilder, Nodes and Secure Parsing
- Introducing XML: Document Structure, Elements and Attributes
- Java Regex Split, Replace and Flags: splitWithDelimiters, replaceAll and Pattern Flags
- Java Regex Matching: matches, find, Groups and Named Groups
- Java Regular Expressions: Syntax, Character Classes and Quantifiers

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.