Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DTD Validation With Python? [duplicate]

I need to validate an XML string (and not a file) against a DTD description file.

How can that be done in python?

like image 404
fulmicoton Avatar asked Nov 25 '22 22:11

fulmicoton


1 Answers

Another good option is lxml's validation which I find quite pleasant to use.

A simple example taken from the lxml site:

from StringIO import StringIO

from lxml import etree

dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>"""))
root = etree.XML("<foo/>")
print(dtd.validate(root))
# True

root = etree.XML("<foo>bar</foo>")
print(dtd.validate(root))
# False
print(dtd.error_log.filter_from_errors())
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content
like image 82
Michael Twomey Avatar answered Jan 03 '23 08:01

Michael Twomey