views:

4296

answers:

4

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.

+1  A: 

lxml provides etree.DTD

from the tests on http://codespeak.net/lxml/api/lxml.tests.test_dtd-pysrc.html

...
root = etree.XML(_bytes("<b/>")) 
dtd = etree.DTD(BytesIO("<!ELEMENT b EMPTY>")) 
self.assert_(dtd.validate(root))
hinoglu
+9  A: 

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.

Keegan Carruthers-Smith
lxml is pure python or not? (does require compilation/installation or you can just include it with your python scripts)
Sorin Sbarnea
@Sorin: lxml is a wrapper on top of the libxml2 C library, and thus is not pure Python.
Eli Courtwright
@eli Exactly what I wanted to underline, this may not be appropriate for anyone.
Sorin Sbarnea
+2  A: 

If you're working with dtd you might enjoy this recipe

poulejapon
+3  A: 

The PyXB package at http://pyxb.sourceforge.net/ generates validating bindings for Python from XML schema documents. It handles almost every schema construct and supports multiple namespaces.

Peter