TExcelTAD
Home › XML › XML Validator

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:

xml · try it yourself
<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
  1. id=c1 — attribute value must be quoted: id="c1".
  2. </Email> — case doesn't match <email>.
  3. Jonas & Partners — a raw & must be written &amp;.

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
bash
$ 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 validate

Writing 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:

html · try it yourself
<!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 &amp; 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?

  1. Every well-formed document is valid
  2. Every valid document is well-formed
  3. Valid and well-formed mean the same
  4. Browsers validate XML against DTDs automatically

What do you need in order to check a document's validity?

  1. Only an XML parser
  2. A DTD or schema describing the format, plus a validating tool
  3. A web server
  4. An XSLT stylesheet

A parser says 'Extra content at the end of the document'. What is the likely cause?

  1. An unquoted attribute
  2. More than one root element
  3. A missing XML declaration
  4. A comment in the document