<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>

[{'answer_id': 15931, 'author': 'Michael Twomey', 'author_id': 995, 'author_profile': 'https://Stackoverflow.com/users/995', 'pm_score': 6, 'selected': True, 'text': '<p>Another good option is <a href="http://lxml.de/validation.html" rel="noreferrer">lxml\'s validation</a> which I find quite pleasant to use.</p>\n\n<p>A simple example taken from the lxml site:</p>\n\n<pre><code>from StringIO import StringIO\n\nfrom lxml import etree\n\ndtd = etree.DTD(StringIO("""&lt;!ELEMENT foo EMPTY&gt;"""))\nroot = etree.XML("&lt;foo/&gt;")\nprint(dtd.validate(root))\n# True\n\nroot = etree.XML("&lt;foo&gt;bar&lt;/foo&gt;")\nprint(dtd.validate(root))\n# False\nprint(dtd.error_log.filter_from_errors())\n# &lt;string&gt;:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content\n</code></pre>\n'}, {'answer_id': 270538, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>from the examples directory in the libxml2 python bindings:</p>\n\n<pre><code>#!/usr/bin/python -u\nimport libxml2\nimport sys\n\n# Memory debug specific\nlibxml2.debugMemory(1)\n\ndtd="""&lt;!ELEMENT foo EMPTY&gt;"""\ninstance="""&lt;?xml version="1.0"?&gt;\n&lt;foo&gt;&lt;/foo&gt;"""\n\ndtd = libxml2.parseDTD(None, \'test.dtd\')\nctxt = libxml2.newValidCtxt()\ndoc = libxml2.parseDoc(instance)\nret = doc.validateDtd(ctxt, dtd)\nif ret != 1:\n    print "error doing DTD validation"\n    sys.exit(1)\n\ndoc.freeDoc()\ndtd.freeDtd()\ndel dtd\ndel ctxt\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/15798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446497/']