Introducing XML: Document Structure, Elements and Attributes
What XML is and how a document is built: the prolog and root element, elements, attributes and text, when to prefer elements over attributes, entity and character references, CDATA, comments and processing instructions, the well-formedness rules, and Java's XML APIs.
kvi5hnuCode Sprout team member11 min readOn this page
Part 3 of the course is about XML, the Extensible Markup Language. XML was once promoted as the answer to every data problem. That hype has faded, and JSON has taken over many of its roles, especially in web APIs. But XML is far from gone. Build files (Maven's pom.xml), office documents (.docx and .xlsx are zip files full of XML), SVG images, Android layouts, RSS and Atom feeds, SOAP services, many configuration formats and countless industry data standards are all XML. Java has strong built-in support for it, and that support is the subject of the next nine articles.
This first article covers the format itself. No Java API is needed yet beyond a parser that tells us whether a document is legal.
Why not a properties file?
Volume I used property files for configuration: flat key=value pairs, read with one call to Properties.load. That's fine until the data has structure. Two problems show up quickly:
- No hierarchy. Related settings get prefixes, like
title.fontnameandtitle.fontsize, and the program has to take the keys apart. - No repetition. Keys must be unique, so lists turn into
menu.item.1,menu.item.2, and so on.
XML expresses both directly:
<config>
<entry id="title">
<font>
<name>Helvetica</name>
<size unit="pt">36</size>
</font>
</entry>
<menu>
<item>Times Roman</item>
<item>Helvetica</item>
</menu>
</config>
Where XML comes from
XML looks like HTML because both descend from SGML, a markup standard from the 1980s used for large technical documents. SGML was powerful but complex, largely because it allowed shortcuts such as omitted end tags. XML 1.0 (a W3C recommendation since 1998, now in its fifth edition) is a strict, simplified subset designed for the web. XML 1.1 exists but is rarely used.
The strictness is the main difference from HTML:
- XML is case-sensitive.
<H1>and<h1>are different tags. - End tags are never optional. In HTML you may leave out
</p>or</li>. In XML you may not. - An element with no content can be written with a single tag ending in
/>, as in<img src="cup.png"/>. It means the same as<img src="cup.png"></img>. - Attribute values must be quoted, with single or double quotes:
width="300", neverwidth=300. - Every attribute needs a value. HTML's
<input checked>must be writtenchecked="checked"orchecked="true".
XHTML was a reformulation of HTML in this strict syntax. Today's HTML5 has its own, lenient parsing rules, so HTML in general can't be read with an XML parser.
The structure of a document

A document has three parts:
- The prolog. It starts with the XML declaration,
<?xml version="1.0" encoding="UTF-8"?>. The declaration is optional, but recommended. When present, it must be the very first thing in the file, not even preceded by white space. Without it, the parser assumes UTF-8 or UTF-16 (it can tell them apart from the first bytes). The prolog may also contain comments, processing instructions and a document type declaration (<!DOCTYPE ...>), which articles 41 and 42 cover. - Exactly one root element that contains everything else.
- Optionally, comments and processing instructions after the root element.
XML files are called "documents" even when they hold data that nobody would call a document. That's another legacy of SGML.
Elements, text and attributes
An element consists of a start tag, content and an end tag. Its content can be text, other elements, or a mix. Elements must nest properly, so <b><i>x</b></i> is illegal. Attributes are name-value pairs in the start tag. Each attribute name may appear only once per element, and their order carries no meaning.
When an element contains both text and child elements, as in
<font>
Helvetica
<size>36</size>
</font>
the specification calls it mixed content. It's natural for prose (an XHTML paragraph with a <b> inside), but for data it makes processing harder. For data, design elements to contain either text or child elements.
Elements or attributes?
The question comes up in every XML design. Compare
<font name="Helvetica" size="36"/>
with
<font>
<name>Helvetica</name>
<size>36</size>
</font>
The attribute version is shorter, but attributes are a dead end. They can't contain structure, they can't repeat, and you can't attach further information to them. If the size later needs a unit, you either cram it into the value (size="36 pt", which brings back the parsing problems XML was supposed to solve) or redesign. With elements, you just add an attribute to size: <size unit="pt">36</size>.
A useful rule of thumb: use attributes for information that modifies how a value is interpreted (units, languages, identifiers, types), and elements for the values themselves. When in doubt, use elements. Many good XML formats use no attributes at all.
Other markup
| Markup | Example | Purpose |
|---|---|---|
| Character reference | é or é | any Unicode character by its decimal or hex code point |
| Entity reference | < > & " ' | the five predefined escapes for < > & " ' |
| CDATA section | <![CDATA[ a < b && c ]]> | text in which < and & aren't markup |
| Comment | <!-- note --> | text for human readers; must not contain -- |
| Processing instruction | <?xml-stylesheet href="s.css" type="text/css"?> | instructions for a particular application |
In text, < and & must always be escaped (or appear in CDATA). > needs escaping only in the sequence ]]>, and quotes only inside attribute values delimited by the same kind of quote. Entity names other than the five predefined ones, like ©, are errors unless a DTD declares them. HTML defines hundreds of named entities, but XML doesn't. Use a character reference such as © instead, or just write the character in UTF-8.
A CDATA section ends at the first ]]>, so it can't contain that string. CDATA is useful for embedding code or markup examples, but it's sometimes abused to smuggle unescaped data into XML. Prefer proper escaping, which any XML library does for you.
Processing instructions look like the XML declaration (<?target data?>), but the declaration isn't one. The names xml, XML and other case variants are reserved. Don't use processing instructions to carry data. Comments should never carry hidden commands either, since parsers are free to drop them.
Well-formed and valid
A document that follows all the syntax rules (one root, proper nesting, quoted attributes, no duplicate attributes, escaped < and &, declared entities) is well-formed. An XML parser must refuse a document that isn't. Unlike browsers with HTML, it isn't allowed to guess what was meant. That strictness is a large part of XML's value: if a document parses, its structure is unambiguous.
A document is valid when it's well-formed and follows the rules of a particular document type, such as which elements may appear where. Articles 41 and 42 show how to describe those rules with DTDs and XML Schema, and how to have the parser check them.
XML support in Java
All the standard XML APIs are in the java.xml module, which is part of every JDK. Together they're called JAXP (Java API for XML Processing):
| API | Package | Covered in |
|---|---|---|
| DOM: read a document into a tree | javax.xml.parsers, org.w3c.dom | article 40 |
| Validation with DTD and XML Schema | javax.xml.validation | articles 41–42 |
| XPath: query a tree | javax.xml.xpath | article 43 |
| SAX: push-style streaming parser | org.xml.sax | article 45 |
| StAX: pull-style streaming parser and writer | javax.xml.stream | articles 45–46 |
| Transformations, XSLT, serializing trees | javax.xml.transform | articles 46–47 |
JAXB, which mapped XML to Java objects through annotations, was removed from the JDK in Java 11 (JEP 320) together with the other Java EE modules. It continues as Jakarta XML Binding, a separate library. This course sticks to the APIs in the JDK.
The program
The demo uses a DOM parser (explained in the next article) only as a well-formedness checker. It first shows the flat keys a properties file needs, then parses the hierarchical version. Then it feeds the parser a series of small documents that break, or follow, the rules above. Each error comes with the line and column where the parser gave up. Last, it shows that the parser honors the encoding in the declaration.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class Solution {
static DocumentBuilder builder;
static void check(String label, String xml) {
try {
Document doc = builder.parse(new InputSource(new StringReader(xml)));
Element root = doc.getDocumentElement();
System.out.printf("%-26s well-formed, root <%s>, text \"%s\"%n", label, root.getTagName(),
root.getTextContent().strip().replaceAll("\\s+", " "));
} catch (SAXParseException e) {
System.out.printf("%-26s ERROR line %d col %d: %s%n", label, e.getLineNumber(), e.getColumnNumber(), e.getMessage());
} catch (SAXException | IOException e) {
System.out.println(label + " " + e);
}
}
public static void main(String[] args) throws Exception {
var factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() { // report errors only through exceptions
public void warning(SAXParseException e) { }
public void error(SAXParseException e) { }
public void fatalError(SAXParseException e) throws SAXException { throw e; }
});
System.out.println("--- a properties file versus XML ---");
var props = new Properties();
props.load(new StringReader("""
title.fontname=Helvetica
title.fontsize=36
menu.item.1=Times Roman
menu.item.2=Helvetica
"""));
System.out.println("flat keys: " + new TreeSet<>(props.stringPropertyNames()));
String config = """
<?xml version="1.0" encoding="UTF-8"?>
<config>
<entry id="title">
<font><name>Helvetica</name><size unit="pt">36</size></font>
</entry>
<menu><item>Times Roman</item><item>Helvetica</item></menu>
</config>""";
check("hierarchical config", config);
System.out.println("--- well-formedness rules ---");
check("case matters", "<Size>36</size>");
check("no omitted end tags", "<list><li>one<li>two</list>");
check("empty element", "<img src=\"cup.png\"/>");
check("unquoted attribute", "<img width=300/>");
check("attribute without value", "<input checked/>");
check("duplicate attribute", "<p a=\"1\" a=\"2\"/>");
check("two roots", "<a/><b/>");
check("overlapping tags", "<b><i>x</b></i>");
check("bare ampersand", "<p>Tom & Jerry</p>");
check("escaped ampersand", "<p>Tom & Jerry <3</p>");
check("character references", "<p>café été</p>");
check("undefined entity", "<p>© 2026</p>");
check("CDATA section", "<code><![CDATA[if (a < b && c > d)]]></code>");
check("comment and PI", "<?xml-stylesheet href=\"s.css\" type=\"text/css\"?><!-- note --><doc>ok</doc>");
check("-- inside comment", "<doc><!-- a -- b --></doc>");
check("header not first", " <?xml version=\"1.0\"?><doc/>");
check("mixed content", "<font>Helvetica<size>36</size></font>");
System.out.println("--- encoding ---");
byte[] latin1 = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><p>naïve</p>"
.getBytes(StandardCharsets.ISO_8859_1);
Document doc = builder.parse(new ByteArrayInputStream(latin1));
System.out.println("declared ISO-8859-1: " + doc.getDocumentElement().getTextContent()
+ ", xmlEncoding=" + doc.getXmlEncoding() + ", version=" + doc.getXmlVersion());
}
}
--- a properties file versus XML ---
flat keys: [menu.item.1, menu.item.2, title.fontname, title.fontsize]
hierarchical config well-formed, root <config>, text "Helvetica36 Times RomanHelvetica"
--- well-formedness rules ---
case matters ERROR line 1 col 11: The element type "Size" must be terminated by the matching end-tag "</Size>".
no omitted end tags ERROR line 1 col 25: The end-tag for element type "li" must end with a '>' delimiter.
empty element well-formed, root <img>, text ""
unquoted attribute ERROR line 1 col 12: Open quote is expected for attribute "width" associated with an element type "img".
attribute without value ERROR line 1 col 15: Attribute name "checked" associated with an element type "input" must be followed by the ' = ' character.
duplicate attribute ERROR line 1 col 15: Attribute "a" was already specified for element "p".
two roots ERROR line 1 col 6: The markup in the document following the root element must be well-formed.
overlapping tags ERROR line 1 col 10: The element type "i" must be terminated by the matching end-tag "</i>".
bare ampersand ERROR line 1 col 9: The entity name must immediately follow the '&' in the entity reference.
escaped ampersand well-formed, root <p>, text "Tom & Jerry <3"
character references well-formed, root <p>, text "café été"
undefined entity ERROR line 1 col 10: The entity "copy" was referenced, but not declared.
CDATA section well-formed, root <code>, text "if (a < b && c > d)"
comment and PI well-formed, root <doc>, text "ok"
-- inside comment ERROR line 1 col 15: The string "--" is not permitted within comments.
header not first ERROR line 1 col 7: The processing instruction target matching "[xX][mM][lL]" is not allowed.
mixed content well-formed, root <font>, text "Helvetica36"
--- encoding ---
declared ISO-8859-1: naïve, xmlEncoding=ISO-8859-1, version=1.0
The error handler in the demo suppresses the default behavior of printing [Fatal Error] messages to standard error. The next article explains error handlers.
Common questions
XML or JSON: which should I use for a new format? JSON for web APIs and simple data exchange: it is lighter, maps directly onto objects, and every language reads it easily. XML when you need mixed content (documents with markup inside text), namespaces to combine vocabularies, mature schema validation, XSLT transformations, or when an industry standard prescribes it. Configuration formats are often YAML, TOML or properties files today, but XML remains common in the Java world, for example in Maven.
How do I put <, & or quotes into element text?
Escape them as <, &, " and ', or let an XML library write the document, which escapes automatically (article 46). Never build XML by concatenating strings with unescaped data; it breaks on the first & and can open injection holes.
Does the order of attributes or of elements matter? Attribute order never matters, and parsers may report attributes in any order. Element order does matter: it is part of the document's meaning, and DTDs and schemas usually prescribe it.
Which encoding should my XML files use? UTF-8, declared in the XML declaration. It is the default when no declaration is present, it handles every character, and all tools support it.
Can I parse HTML with an XML parser?
Only XHTML or HTML that happens to be well-formed. Real-world HTML omits end tags, leaves attributes unquoted and uses entities like that XML does not know. Use an HTML parser such as jsoup for web pages.
Summary
- XML describes hierarchical, repeating data that flat property files can't express cleanly.
- It's stricter than HTML: case-sensitive, mandatory end tags or
/>, quoted attribute values, no attributes without values. - A document has a prolog (XML declaration first, then optionally a DOCTYPE), exactly one root element, and properly nested elements that contain text, child elements or both. Avoid mixed content in data formats.
- Prefer elements for values and attributes for metadata about values.
- Escape
<and&with<and&. Character references (é) encode any character, and CDATA sections hold unescaped text. - Parsers reject documents that aren't well-formed. Validity against a DTD or schema is a separate, optional check.
- The JDK's
java.xmlmodule provides DOM, SAX, StAX, XPath, validation and XSLT. JAXB is no longer part of the JDK.
Practice Questions
Rewrite this HTML fragment as well-formed XML: \<P\>Size: \<input type=text value=36 disabled\>\<br\>\</p\>
<p>Size: <input type="text" value="36" disabled="disabled"/><br/></p>. The start and end tags must match in case, attribute values need quotes, disabled needs a value, and the empty elements input and br need the /> form or an explicit end tag.
Is \<price currency="USD" amount="12.50"/\> a good design? What problems might it cause later?
It works, but both values are packed into attributes. If you later need structure, such as a tax breakdown or several amounts, attributes can't hold it, and you can't qualify an attribute with further attributes. A more flexible design is <price currency="USD">12.50</price>, where currency modifies how the value is interpreted, or a price element with child elements.
Which characters must be escaped in XML text, and how do you write if (a \< b && c) inside an element?
< and & must always be escaped in text. > only in the sequence ]]>, and quotes only inside attribute values. Write <cond>if (a < b && c)</cond> or use a CDATA section: <cond><![CDATA[if (a < b && c)]]></cond>.
Why does a parser reject in an XML document even though browsers accept it?
XML predefines only five entities: lt, gt, amp, quot and apos. is an HTML entity. In XML it must be declared in a DTD, or replaced by the character reference   (or the actual no-break space character).
What's the difference between a well-formed and a valid XML document?
A well-formed document follows XML's syntax rules, which every XML parser enforces. A valid document is well-formed and conforms to a specific grammar, given by a DTD or XML Schema, that says which elements and attributes may appear, in which order and with which content. Validation is optional and must be requested.
Previous: Java Regex Split, Replace and Flags: splitWithDelimiters, replaceAll and Pattern Flags
Next: Parsing XML with DOM: DocumentBuilder, Nodes and Secure Parsing
Related reading
- 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
- Java Serialization: readResolve, writeReplace, Versioning and Security
- Customizing Java Serialization: transient, readObject, writeObject and Externalizable

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.