How to validate XML against an XSD: xmllint, PowerShell and common errors
Checkcraft is a desktop app for checking APIs and logs without code, with a free edition. Download, no sign-up →
Online validators ask you to upload the file to someone else’s server, and XML often contains company details and personal data. You can validate it against the schema locally with one command.
Linux and macOS: xmllint
xmllint ships with libxml2 and is usually installed already; on Debian and Ubuntu it is in the libxml2-utils package. The command validates the file against the schema and names the line for each error. With no errors, it reports that the file validates.
xmllint --noout --schema schema.xsd file.xmlWindows: PowerShell with nothing to install
On Windows the built-in .NET platform does the validation. Save the script next to the files and run it in PowerShell: it prints each error with its line number. No output means the file matches the schema.
# Windows PowerShell: validate file.xml against schema.xsd
$xml = (Resolve-Path "file.xml").Path
$xsd = (Resolve-Path "schema.xsd").Path
$settings = New-Object System.Xml.XmlReaderSettings
$settings.ValidationType = [System.Xml.ValidationType]::Schema
$settings.Schemas.Add($null, $xsd) | Out-Null
$settings.add_ValidationEventHandler({ param($s, $e) Write-Host "$($e.Severity): line $($e.Exception.LineNumber): $($e.Message)" })
$reader = [System.Xml.XmlReader]::Create($xml, $settings)
while ($reader.Read()) { }
$reader.Close()Typical errors
An element is not expected here: the order is broken or the tag name differs from the schema. A required element is missing: the XML lacks a tag the schema demands. A value does not match its type or pattern: a date not in YYYY-MM-DD, extra spaces or the wrong length. Namespace errors mean the xmlns in the file does not match the schema targetNamespace.
When the XML comes from an API
If the XML is a SOAP or REST response, besides the schema you need to check values: the result code, totals, the presence of a Fault. Checkcraft does not validate against XSD, but it checks the tags and values you need with XML rules and no code.
Repeat this on your own API
Checkcraft is a desktop app that saves API response checks without code and shows what did not match. Start with a sample, then use your own sanitized data. Free runs on Windows and Linux with no time limit.
Download FreeDownload and first runNo sign-up or email needed, the archive is ready in a couple of minutes. See the edition limits.
References
Start with the linked example and compare its result with your own test requirement.