How do I validate xml against a DTD file in Python
Asked Answered
B

2

31

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

How can that be done in python?

Bugeye answered 19/8, 2008 at 6:24 Comment(0)
H
33

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
Heinous answered 19/8, 2008 at 9:39 Comment(0)
G
7

from the examples directory in the libxml2 python bindings:

#!/usr/bin/python -u
import libxml2
import sys

# Memory debug specific
libxml2.debugMemory(1)

dtd="""<!ELEMENT foo EMPTY>"""
instance="""<?xml version="1.0"?>
<foo></foo>"""

dtd = libxml2.parseDTD(None, 'test.dtd')
ctxt = libxml2.newValidCtxt()
doc = libxml2.parseDoc(instance)
ret = doc.validateDtd(ctxt, dtd)
if ret != 1:
    print "error doing DTD validation"
    sys.exit(1)

doc.freeDoc()
dtd.freeDtd()
del dtd
del ctxt
Geof answered 6/11, 2008 at 22:17 Comment(1)
Note that the libxml2 bindings are not part of the Python standard library, i.e. not built in.Bearded

© 2022 - 2024 — McMap. All rights reserved.