How-to
How to validate XML against an XSD
To validate XML against an XSD, give a schema-aware validator both files and read the errors it reports. On a Mac, Terminal already has one: xmllint --noout --schema schema.xsd file.xml prints "file.xml validates" or the line and rule each element breaks. Most failures come from a namespace that does not match the schema's targetNamespace, elements in the wrong order, or values of the wrong type.
1. What does validating against an XSD check?
Validation checks that an XML document follows the rules in a particular XML Schema: which root element is allowed, which child elements appear and in what order, how often each repeats, which attributes are required, and what type each value must have. It is a contract check, so the same file can pass one schema and fail another.
It runs after a simpler check. A document has to be well-formed XML first, with matching tags and one root element. If it is not, the parser stops before any schema rule is tested, and you see a parser error instead of a validation error. Fix those first.
The examples on this page use the small schema and document below. Save them as order.xsd and order.xml in the same folder to follow along. The schema declares one root element, order, in the namespace urn:example:orders, with a required id attribute, a customer, a positive whole-number quantity, and an optional note, in that order.
<?xml version="1.0" encoding="UTF-8"?>
<!-- order.xsd -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:example:orders"
xmlns="urn:example:orders"
elementFormDefault="qualified">
<xs:element name="order">
<xs:complexType>
<xs:sequence>
<xs:element name="customer" type="xs:string"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="id" type="xs:positiveInteger" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
<?xml version="1.0" encoding="UTF-8"?>
<!-- order.xml -->
<order xmlns="urn:example:orders" id="1042">
<customer>Ada Lovelace</customer>
<quantity>3</quantity>
</order>2. How do I validate XML against an XSD on a Mac?
Use xmllint, which macOS includes at /usr/bin/xmllint, so there is nothing to install. Pass the schema with --schema and add --noout so it prints only the result instead of echoing the whole document back.
A valid file prints one line ending in validates and exits with status 0. An invalid file prints one line per problem, each with the line number, the element, and the rule it breaks, then a final fails to validate line, and exits with status 3. That exit status lets a script or a build step stop when a file is invalid.
You can list several XML files after the schema to check them in one run. Note that --valid is a different option: it validates against a DTD, not an XSD.
# Validate one file
$ xmllint --noout --schema order.xsd order.xml
order.xml validates
$ echo $?
0
# Validate several files against the same schema
$ xmllint --noout --schema order.xsd order.xml order-1043.xml
order.xml validates
order-1043.xml:4: element quantity: Schemas validity error : Element '{urn:example:orders}quantity': 'three' is not a valid value of the atomic type 'xs:positiveInteger'.
order-1043.xml fails to validate3. How to read XSD validation errors
Each message names the element in {namespace}name form, so you can see both which element failed and which namespace the validator thinks it is in. These are the messages you will meet most often, with the actual xmllint wording and the usual fix:
<!-- order-bad.xml: two mistakes -->
<order xmlns="urn:example:orders">
<quantity>3</quantity>
<customer>Ada Lovelace</customer>
</order>
$ xmllint --noout --schema order.xsd order-bad.xml
order-bad.xml:2: element order: Schemas validity error : Element '{urn:example:orders}order': The attribute 'id' is required but missing.
order-bad.xml:3: element quantity: Schemas validity error : Element '{urn:example:orders}quantity': This element is not expected. Expected is ( {urn:example:orders}customer ).
order-bad.xml fails to validate- "This element is not expected. Expected is ( {urn:example:orders}customer )." An element appeared where the schema does not allow it. In an xs:sequence the order matters, so this usually means two children are swapped, an element is misspelled, or an element the schema does not declare was added. The expected list tells you what may come next.
- "Missing child element(s). Expected is ( {urn:example:orders}quantity )." A required child is absent. Elements without minOccurs="0" must appear at least once.
- "'three' is not a valid value of the atomic type 'xs:positiveInteger'." The text does not match the declared type. Common causes are words instead of numbers, a comma as the decimal separator, dates not in YYYY-MM-DD form for xs:date, and stray spaces in restricted string types.
- "The attribute 'id' is required but missing." An attribute declared with use="required" is absent from the element.
- "No matching global declaration available for the validation root." The validator found no top-level declaration for the root element in the namespace it is in. This is almost always a namespace problem; the next section explains it.
4. Fix "No matching global declaration available for the validation root"
The root element's namespace must be the schema's targetNamespace. The W3C XML Schema specification has a validator build its schema from documents whose targetNamespace is identical to the namespace of the element being checked, so an order element with no namespace does not match a schema for urn:example:orders, even though the names look the same.
Compare the xmlns on your root element with targetNamespace on xs:schema. If the schema has a targetNamespace, add the matching default namespace declaration to the root. If the schema has no targetNamespace, the document's elements must have no namespace either. Also check elementFormDefault: when it is qualified, as here, child elements inherit the namespace and must stay in it; a child redeclared with xmlns="" fails.
<!-- Fails: order is in no namespace -->
<order id="1042">...</order>
order.xml:2: element order: Schemas validity error : Element 'order': No matching global declaration available for the validation root.
<!-- Passes: order is in the schema's targetNamespace -->
<order xmlns="urn:example:orders" id="1042">...</order>5. xsi:schemaLocation tells tools where the schema is, as a hint
A document can name its own schema. Declare the XML Schema instance namespace, then use xsi:schemaLocation with pairs of namespace URI and schema file, or xsi:noNamespaceSchemaLocation with a single file when the schema has no targetNamespace. Relative paths are resolved against the XML file's location.
These attributes are hints, not commands. The specification leaves how a validator locates schemas to the processor, and tools differ. Editors such as Visual Studio and VS Code with the Red Hat XML extension read the hints and validate as you type. xmllint does not: xmllint --noout order.xml without --schema only checks that the file is well-formed, even when xsi:schemaLocation is present, and prints nothing either way. Pass the schema explicitly when you need a real validation result.
Many schemas are split into several files with xs:include and xs:import. Keep the whole schema folder together as delivered, and validate against the main file that declares the root element.
<order xmlns="urn:example:orders"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:example:orders order.xsd"
id="1042">
<customer>Ada Lovelace</customer>
<quantity>3</quantity>
</order>
<!-- For a schema with no targetNamespace -->
<invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="invoice.xsd">...</invoice>6. Validate XML against an XSD in Visual Studio or VS Code
In Visual Studio on Windows, open the XML file and set the Schemas field in the document's Properties window to the .xsd file, or rely on xsi:schemaLocation in the document. The XML editor validates as you type: blue wavy underlines mark schema errors, red ones mark well-formedness errors, and each appears in the Error List. Visual Studio for Mac was retired in 2024, so on a Mac use Visual Studio Code instead.
In Visual Studio Code on macOS, Windows, or Linux, install the XML extension by Red Hat. It validates a document that names its schema through xsi:schemaLocation or xsi:noNamespaceSchemaLocation. For files that do not, map them to a schema in settings.json with xml.fileAssociations, which takes a file pattern and the schema's systemId. When the schema has a targetNamespace, the association only applies to documents that declare that namespace.
// .vscode/settings.json
{
"xml.fileAssociations": [
{ "pattern": "orders/*.xml", "systemId": "schemas/order.xsd" }
]
}7. Validate XML against an XSD in Python or C#
When validation belongs in an import job or a test, use your language's XML library. In Python, lxml compiles the schema with etree.XMLSchema; validate returns True or False, and error_log holds each message with its line number. lxml uses libxml2, the same library as xmllint, so the messages read the same.
In .NET, add the schema to XmlReaderSettings.Schemas with its target namespace, set ValidationType to Schema, and read the document through XmlReader.Create. Each problem raises the ValidationEventHandler, so you can collect every error instead of stopping at the first. As with every validator, the document's namespace must match the schema's target namespace.
# Python (pip install lxml)
from lxml import etree
schema = etree.XMLSchema(etree.parse("order.xsd"))
doc = etree.parse("order.xml")
if not schema.validate(doc):
for error in schema.error_log:
print(f"line {error.line}: {error.message}")
// C# (System.Xml)
var settings = new XmlReaderSettings();
settings.Schemas.Add("urn:example:orders", "order.xsd");
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += (sender, e) =>
Console.WriteLine($"{e.Severity}: {e.Message}");
using var reader = XmlReader.Create("order.xml", settings);
while (reader.Read()) { }8. Validate and fix the file in one window on a Mac
Terminal tells you which line failed; you still switch to an editor to fix it and run the command again. In XML Lens, the validation workspace checks the open document against an XSD you select locally, shows well-formedness feedback and each validation error, and shows a success state once the document passes. Fix the source in the editor, validate again, and the document and schema stay on your Mac.
If the schema itself is the problem, open it in XSD Viewer to browse its structure tree and global declarations, search names and types, and compile it to see diagnostics with source context. XSD Viewer is a separate workspace from validation, so inspecting the schema does not change the document you are checking. For a folder of exports, Batch processing can run validation across selected files and writes results to an output folder you choose, without overwriting the originals.
9. Limits of XSD validation
A schema pass is useful evidence, but it is not proof that a receiving system will accept the file.
- XSD 1.1 features: assertions (xs:assert) and conditional type assignment need an XSD 1.1 processor. xmllint and XML Lens do not claim XSD 1.1 support, so a correct 1.1 schema can fail to compile in them.
- Remote schema files: some schemas import other files from a URL. Offline tools, and XML Lens, which does not fetch remote schema resources, need local copies of every file.
- Business rules: the example schema accepts any positive quantity. Rules such as stock limits, totals that add up, or IDs that exist in another system need checks outside the schema.
- Online validators: a web XSD validator is fine for public samples, but uploading a partner's invoice or a customer export sends that data to someone else's server. Use a local validator for confidential files.
Common questions
How do I validate XML against an XSD in Visual Studio?
Open the XML file in Visual Studio on Windows and set the Schemas field in its Properties window to the .xsd, or add xsi:schemaLocation to the root element. Schema errors appear as blue wavy underlines and in the Error List.
Is xmllint already installed on a Mac?
Yes. macOS includes xmllint at /usr/bin/xmllint. Run xmllint --noout --schema schema.xsd file.xml in Terminal to validate a file.
Why does my XML fail with "No matching global declaration available for the validation root"?
The root element is not in the schema's targetNamespace, or the schema does not declare that element at the top level. Make the root element's xmlns match targetNamespace exactly and validate against the schema file that declares the root.
Does xmllint use xsi:schemaLocation?
Not for validation from the command line. Without --schema, xmllint only checks that the document is well-formed, so pass the schema explicitly to get a validation result.
Can I validate XML against an XSD online?
Yes, online validators accept a pasted XML file and schema. Use them only for public or sample data; for invoices, customer exports or partner files, validate locally with xmllint, an editor, or a desktop app.
References
W3C XML Schema Part 1: Structures, 4.3.2 How schema definitions are located on the Web ↗W3C XML Schema Part 0: Primer ↗libxml2 xmllint manual ↗Microsoft: XML document validation in the Visual Studio XML editor ↗Microsoft: XML Schema (XSD) validation with XmlSchemaSet ↗Red Hat vscode-xml: Validation with XSD grammar ↗Microsoft: What happened to Visual Studio for Mac? ↗lxml: Validation with lxml ↗Try the workflow in XML Lens
XML Lens is a native Mac app for viewing, validating, querying and comparing XML that keeps your files on your Mac. It is listed as XML Editor Lens: XPath on the Mac App Store.
Download XML Lens for MacExplore the relevant Mac workspaces and their capabilities.
Validate XML and run local XSLT 1.0 on Mac View and map XML Schema (XSD) locally on Mac Batch-process XML files on Mac without overwriting originals