python使用xmlproc验证xml格式是否符合DTD定义,xmlprocdtd,PyXML是一个解析xm


PyXML是一个解析xml的python包,它的xmlval和xmldtd模块可以用来验证xml文档是否符合dtd文件的定义。

下面是一个简单的示例:

from xml.parsers.xmlproc import xmlprocfrom xml.parsers.xmlproc import xmlvalfrom xml.parsers.xmlproc import xmldtd# code to handle XML parsing goes hereclass MyApp(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# XML file and corresponding DTD definitionfile = 'test.xml'dtd  = 'test.dtd'# standard XML parsing, without validation against DTDprint 'Start XML Parsing (No DTD)'p = xmlproc.XMLProcessor()p.set_application(MyApp())p.parse_resource(file)print 'End XML Parsing (No DTD)'print# XML parsing, with validation against external DTD# Since you are referencing an external DTD from # test.xml, you'll need markers like:# #  <?xml version="1.0"?>#  <!DOCTYPE base SYSTEM "test.dtd">## (where 'base' is the root element of the XML doc) # at the top of your XML docprint 'Start XML Parsing (With DTD)'d = xmldtd.load_dtd(dtd)p = xmlval.XMLValidator()p.set_application(MyApp())p.parse_resource(file)print 'End XML Parsing (With DTD)'

评论关闭