Validation at Runtime

At runtime, one means of validating XML documents from Python is using xmlproc in conjunction with its callback interfaces and parser API. By implementing both the ErrorHandler and DTDConsumer interfaces, you can capture events about validity errors within the document (via ErrorHandler) and events about the DTD’s structure (via DTDConsumer).

To catch errors in the validity of the document, you can implement the ErrorHandler interface and provide it to the XMLValidator, all part of xmlproc. Create the file xpHandlers.py and add the BadOrderErrorHandler class to it, as shown in Example 7-4.

Example 7-4. A BadOrderErrorHandler class implements ErrorHandler in xpHandlers.py

from xml.parsers.xmlproc.xmlapp import DTDConsumer
from xml.parsers.xmlproc.xmlapp import ErrorHandler

"""
BadOrderErrorHandler -- implement xmlproc's ErrorHandler Interface
"""
class BadOrderErrorHandler(ErrorHandler):
  def warning(self,msg):
    print "Warning received!:", msg

  def error(self,msg):
    print "Error received!: ", msg

  def fatal(self,msg):
    print "Fatal Error received!: ", msg

To catch events related to the construction of the DTD itself, you can implement the DTDConsumer interface. In order to do this, add the class to xpHandlers.py, as shown in Example 7-5.

Example 7-5. A DTDHandler class implements DTDConsumer in xpHandlers.py

""" DTDHandler -- implements xmlproc's DTDConsumer Interface """ class DTDHandler(DTDConsumer): def __init__(self,parser): self.parser=parser def dtd_start(self): ...

Get Python & XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.