Well-Formed vs Valid XML
'Well-formed' and 'valid' are two distinct, precise terms in XML — a document can follow all the syntax rules (well-formed) without matching a specific expected structure (valid).
Two Different Standards
A well-formed document simply obeys XML's basic syntax rules — proper nesting, matching tags, a single root. A valid document goes further: it must also conform to a specific structure defined by a DTD or XML Schema (covered in the next two lessons), specifying which elements are allowed, in what order, and how many times.
An Example
The document below is perfectly well-formed — its syntax is correct — but it might still be considered invalid if a schema requires a <price> element that's missing here.
<product>
<name>Desk Lamp</name>
</product>
<!-- Well-formed: yes. Valid against a schema requiring <price>: no. -->
Common Mistakes
- Assuming a well-formed document is automatically correct for its intended purpose — well-formedness says nothing about whether the right elements are present.
- Skipping schema or DTD validation for documents exchanged between different systems, allowing structurally incomplete data through.
- Confusing the two terms in conversation, leading to ambiguity about what has actually been checked.
- Assuming every XML document needs a DTD or schema — many simple, well-formed documents are used successfully without one.
Professional Tip
When integrating with another system's XML, always ask specifically whether documents need to be 'well-formed' or 'valid against a schema' — the two checks catch very different classes of problems.
Your Turn
Take the product example above and add a
Mini Quiz
What does it mean for an XML document to be 'valid' (as opposed to merely 'well-formed')?