Wednesday, May 30, 2007

Validating XML with a DTD and python.

Below is a way to validate an XML file using python and an external DTD.

Are there any other ways to do XML DTD validation with python?

A DTD is one way of specifying how an XML should be formed - a schema for XML documents.


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

def validate_xml(xml_filename, dtd_filename):
"""Validate a given XML file with a given external DTD.
If the XML file is not valid, an exception will be
printed with an error message.
"""
dtd = xmldtd.load_dtd(dtd_filename)
parser = xmlproc.XMLProcessor()
parser.set_application(xmlval.ValidatingApp(dtd, parser))
parser.dtd = dtd
parser.ent = dtd
parser.parse_resource(xml_filename)


if __name__ == "__main__":
import sys
xml_filename, dtd_filename = sys.argv[1], sys.argv[2]
validate_xml(xml_filename, dtd_filename)






Melbourne Web Developer Written by a Melbourne web developer. Available for your projects - php, mysql, e commerce, javascript, CMS, css, flash, actionscript, python, games, postgresql, xml.

2 comments:

polaar said...

Have a look at lxml: it's a pythonic binding for libxml/libxslt. It uses the elementtree api but offers additional features over the etree package you find in the standard lib, including validation (with dtd, xsd and relax ng)

Bablu said...

Hi,
I validate my code with schema , getting errors . So I tried DTD still some unresolved error. this is my code "URL: http://rafb.net/p/VzmEsE80.html"

advanced thanks,
pradeep