Validate XML Against an XSD File With xmllint

An XML document can be well formed but still violate its schema. The example stays syntactically valid when seats changes from 2 to 0, but that change breaks the XSD rule that the count must be a positive integer.

Worked example

Create and validate a synthetic booking document

sample_dir=$(mktemp -d) && cd "$sample_dir" || exit 1
cat >order.xsd <<'XSD'
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="seats" type="xs:positiveInteger"/>
</xs:schema>
XSD
cat >order.xml <<'XML'
<seats>2</seats>
XML
xmllint --nonet --noout --schema order.xsd order.xml

Steps

  1. Put the XML document and the XSD provided by the system accepting it into the same working directory. For a local test, paste the example into a shell with xmllint installed; it creates both files in a temporary directory.
  2. Run xmllint --nonet --noout --schema order.xsd order.xml. The sample should validate; change the seats value to 0 and run the command again to see the schema error.
  3. When validating your own documents, distinguish a schema compilation error from a bad value in the XML. Check the schema version, namespaces, and any schema dependencies before editing the document.

What to check

  • Omitting --schema only checks the XML itself. Confirm the schema validation command returns a nonzero status for the edited value even though the tags still match.
  • The sample is self-contained. If your XSD imports other schema files, obtain trusted local copies and verify their paths. A missing dependency can stop validation before it checks the document.

References