XML Validator
There are two levels of "correct" for an XML document:
| Level | Question it answers | Checked by |
|---|---|---|
| Well-formed | Does it follow XML's grammar? (closed tags, proper nesting, quoted attributes …) | Every XML parser, always |
| Valid | Does it follow the rules of this particular format? (which elements, in what order, what values) | A validating parser plus a DTD or schema |
Every valid document is well-formed, but a well-formed document is not necessarily valid.
Checking well-formedness
The playgrounds on ExcelTAD use the browser's parser as a well-formedness checker. This document has three mistakes — fix them one at a time, running after each fix:
<contacts>
<contact id=c1>
<name>Amara Diallo</name>
<email>amara@example.com</Email>
</contact>
<contact id="c2">
<name>Jonas & Partners</name>
</contact>
</contacts>Show the three mistakes
id=c1— attribute value must be quoted:id="c1".</Email>— case doesn't match<email>.Jonas & Partners— a raw&must be written&.
A parser stops at the first fatal error, so you often fix problems one by one.
Common well-formedness errors
| Error message (roughly) | Usual cause |
|---|---|
| Opening and ending tag mismatch | Typo or wrong case in an end tag, or bad nesting |
| Premature end of data / no root element | Missing end tags, or an empty file |
| Extra content at the end of the document | More than one root element |
AttValue: " or ' expected |
Unquoted attribute value |
| Attribute redefined | The same attribute twice on one element |
| xmlParseEntityRef: no name | A raw & in text |
| StartTag: invalid element name | Name starts with a digit, or a raw < in text |
| XML declaration allowed only at the start | Whitespace, a blank line or a comment before <?xml |
Checking validity
Validity needs a description of the format — a DTD or an XML Schema (XSD) — and a validating tool. Browsers parse XML but don't validate it, so validation usually happens in an editor, a build step or on the server:
| Tool | Validates with |
|---|---|
xmllint --noout --schema books.xsd books.xml (libxml2, command line) |
DTD, XSD, RELAX NG |
| VS Code with the "XML" extension (Red Hat) | DTD, XSD — errors shown as you type |
Python lxml.etree.XMLSchema |
XSD, DTD, RELAX NG |
Java javax.xml.validation |
XSD |
.NET XmlReaderSettings.ValidationType |
XSD, DTD |
$ xmllint --noout --schema contacts.xsd contacts.xml
contacts.xml:4: element phone: Schemas validity error : Element 'phone': This element is not expected. Expected is ( email ).
contacts.xml fails to validateWriting your own checks
Sometimes you just need a few business rules checked in the browser — for example before uploading a file. You can write them with DOM queries:
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<contacts>
<contact id="c1"><name>Amara Diallo</name><email>amara@example.com</email></contact>
<contact id="c2"><name>Jonas & Partners</name></contact>
<contact id="c1"><name></name><email>not-an-email</email></contact>
</contacts>`;
function validate(text) {
const doc = new DOMParser().parseFromString(text, 'application/xml');
if (doc.querySelector('parsererror')) return ['Not well-formed'];
const problems = [];
const seen = new Set();
doc.querySelectorAll('contact').forEach((c, i) => {
const where = `contact #${i + 1}`;
const id = c.getAttribute('id');
if (!id) problems.push(`${where}: missing id`);
else if (seen.has(id)) problems.push(`${where}: duplicate id "${id}"`);
seen.add(id);
const name = c.querySelector('name');
if (!name || !name.textContent.trim()) problems.push(`${where}: name is required`);
const email = c.querySelector('email');
if (!email) problems.push(`${where}: email is required`);
else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.textContent)) problems.push(`${where}: bad email "${email.textContent}"`);
});
return problems;
}
const problems = validate(xml);
console.log(problems.length ? problems.join('\n') : 'Valid!');
</script>
</body>
</html>This is exactly the kind of rule that a DTD or schema expresses declaratively — which is what the next two lessons cover.
Tip: Validate early. Checking a file when it arrives (and rejecting it with a clear message) is far cheaper than discovering bad data deep inside your application.
Test yourself
Which statement is true?
- Every well-formed document is valid
- Every valid document is well-formed
- Valid and well-formed mean the same
- Browsers validate XML against DTDs automatically
What do you need in order to check a document's validity?
- Only an XML parser
- A DTD or schema describing the format, plus a validating tool
- A web server
- An XSLT stylesheet
A parser says 'Extra content at the end of the document'. What is the likely cause?
- An unquoted attribute
- More than one root element
- A missing XML declaration
- A comment in the document