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!: ", msgTo 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): ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access