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

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.


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…
I validate my code with schema , getting errors . So I tried DTD still some unresolved error. this is my code "URL:"

advanced thanks,

Popular posts from this blog

Is PostgreSQL good enough?

Experiments with new low latency PyPy garbage collector in a thread.

🐱‍🏍 — the first pygame 2 community game. Starting now! Are you in?