首页 » 编程开发 » Python » 正文

Python中如何对xml文件或xml字符串进行DTD验证

DTD 是一套关于标记符的语法规则。它是XML1.0版规格得一部分,是XML文件的验证机制,属于XML文件组成的一部分。
DTD 是一种保证XML文档格式正确的有效方法,可以通过比较XML文档和DTD文件来看文档是否符合规范,元素和标签使用是否正确。一个DTD文档包含:元素的定义规则,元素间关系的定义规则,元素可使用的属性,可使用的实体或符号规则。
当需要验证的是xml文件时,可以使用xmlproc 进行验证,例子如下:

from xml.parsers.xmlproc import xmlproc
from xml.parsers.xmlproc import xmlval
from xml.parsers.xmlproc import xmldtd

class validate(xmlproc.Application):
def handle_start_tag(self,name,attrs):
pass
def handle_end_tag(self,name):
pass
def handle_data(self,data,start,end):
pass
def handle_comment(self,data):
pass
file = ‘mytest.xml’
dtd = ‘mytest.dtd’
print ‘Start XML Parsing (With DTD)’
d = xmldtd.load_dtd(dtd)
p = xmlval.XMLValidator()
p.set_application(validate())
p.parse_resource(file)
print ‘End XML Parsing (With DTD)’

当需要验证的xml字符串时,参考下面的例子:

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())
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content

以上就是在python中对XML进行DTD验证的两种方法。

发表评论