How do I validate xml against a DTD file in Python
<p>I need to validate an XML string (and not a file)
against a DTD description file. </p>

<p>How can that be done in <code>python</code>?</p>

<p>Another good option is <a href="http://lxml.de/validation.html" rel="nofollow">lxml's validation</a> which I find quite pleasant to use.</p>

<p>A simple example taken from the lxml site:</p>

<pre><code>from StringIO import StringIO

from lxml import etree

dtd = etree.DTD(StringIO("""&lt;!ELEMENT foo EMPTY&gt;"""))
root = etree.XML("&lt;foo/&gt;")
print(dtd.validate(root))
# True

root = etree.XML("&lt;foo&gt;bar&lt;/foo&gt;")
print(dtd.validate(root))
# False
print(dtd.error_log.filter_from_errors())
# &lt;string&gt;:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content
</code></pre>
