如何在Python中针对DTD文件验证xml [英] How do I validate xml against a DTD file in Python
本文介绍了如何在Python中针对DTD文件验证xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要针对DTD描述文件验证XML字符串(而不是文件)
。
I need to validate an XML string (and not a file) against a DTD description file.
如何在 python
中完成?
推荐答案
另一个不错的选择是 lxml的验证,我觉得这很愉快
Another good option is lxml's validation which I find quite pleasant to use.
一个简单的示例,取自lxml网站:
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
这篇关于如何在Python中针对DTD文件验证xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文