我需要针对DTD描述文件验证XML字符串(而不是文件).
怎么办python
?
另一个不错的选择是lxml的验证,我发现它非常令人愉快.
从lxml站点获取的一个简单示例:
from StringIO import StringIO from lxml import etree dtd = etree.DTD(StringIO("""""")) root = etree.XML("") print(dtd.validate(root)) # True root = etree.XML(" bar ") print(dtd.validate(root)) # False print(dtd.error_log.filter_from_errors()) #:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content
来自libxml2 python绑定中的examples目录:
#!/usr/bin/python -u import libxml2 import sys # Memory debug specific libxml2.debugMemory(1) dtd="""""" instance="""""" 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