如何验证XML对Python中的DTD文件(How do I validate xml agains

2019-08-19 07:33发布

我需要验证针对DTD描述文件的XML字符串(而不是文件)。

如何在做python

Answer 1:

另一个很好的选择是LXML的验证 ,我觉得很愉快的使用。

从LXML网站采取一个简单的例子:

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


Answer 2:

从libxml2的Python绑定的例子目录:

#!/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


文章来源: How do I validate xml against a DTD file in Python