I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?
I'd prefer something using the standard library, but I can install a third-party package if necessary.
You can easily validate an XML file or tree against an XML Schema (XSD) with the xmlschema Python package. It's pure Python, available on PyPi and doesn't have many dependencies. The method raises an exception if the file doesn't validate against the XSD.
You can validate your XML documents against XML schemas only; validation against DTDs is not supported.
Just try to parse it with ElementTree (xml. etree. ElementTree. fromstring) - it will raise an error if the XML is not well formed.
I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check Validation with lxml. The page also lists how to use lxml to validate with other schema types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With