如何在 Python 中针对 DTD 文件验证 xml [英] How do I validate xml against a DTD file in Python

查看:25
本文介绍了如何在 Python 中针对 DTD 文件验证 xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何在 python 中做到这一点?

How can that be done in 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆