XML technologies / XML / Python & XML / XML validation and dialects / Runtime validation
(Excerpt from "Python & XML" by Christopher A. Jones & Fred L. Drake, Jr.)
One way to validate XML documents at runtime in Python is xmlproc with its callback interfaces and parser API. By implementing the ErrorHandler and DTDConsumer interfaces, you can catch events concerning validity errors in the document or the DTD structure.
To catch validity errors in a document, you can implement the interface ErrorHandler and pass it to the XMLValidator; both are part of xmlproc. Create the file xpHandlers.py and add the class BadOrder ErrorHandler as shown in the following example.
Example: A BadOrderErrorHandler class implements ErrorHandler in xpHandlers.py
from xml.parsers.xmlproc.xmlapp import DTDConsumer
from xml.parsers.xmlproc.xmlapp import ErrorHandler
"""
BadOrderErrorHandler -- implementiert ErrorHandler-Schnittstelle aus xmlproc
"""
class BadOrderErrorHandler(ErrorHandler):
def warning(self,msg):
print "Warnung erhalten!:", msg
def error(self,msg):
print "Fehler erhalten!: ", msg
def fatal(self,msg):
print "Kritischen Fehler erhalten!: ", msg
To catch events concerning the construction of the DTD itself, you can implement the interface DTDConsumer. To do so, add the class DTDHandler to the file xpHandlers.py as shown in the following example.
Example: A DTDHandler class implements DTDConsumer in xpHandlers.py
"""
DTDHandler -- implementiert DTDConsumer-Schnittstelle aus xmlproc
"""
class DTDHandler(DTDConsumer):
def __init__(self,parser):
self.parser=parser
def dtd_start(self):
print "Start der DTD..."
def dtd_end(self):
print "Ende der DTD..."
def new_general_entity(self,name,val):
print "Allgemeine Entity erhalten: ", name
def new_external_entity(self,ent_name,pub_id,sys_id,ndata):
print "Externe Entity erhalten: ", ent_name
def new_element_type(self,elem_name,elem_cont):
print "Neue Elementtyp-Deklaration: ", elem_name
print "Inhaltsmodell: ", elem_cont
def new_attribute(self,elem,attr,a_type,a_decl,a_def):
print "Neue Attribut-Deklaration: ", attrThis example is self-explanatory. Each method represents an event while parsing the DTD. Your methods can capture this information and use it in any way you choose.
The actual work is done when implementing the interfaces. To do useful work and use the validator, you can create an instance, pass it your interface objects, and direct it at a particular resource. The file shown in the next example val.py contains the small amount of code needed to parse a document.
Example: Command-line validator (val.py)
""" XML-Validierung """
import sys
from xml.parsers.xmlproc import xmlval
from xpHandlers import BadOrderErrorHandler, DTDHandler
xv = xmlval.XMLValidator( )
dt = DTDHandler(xv.parser)
bh = BadOrderErrorHandler(xv.app.locator)
xv.set_error_handler(bh)
xv.set_dtd_listener(dt)
xv.parse_resource(sys.argv[1])You can use val.py from the command line to see whether XML documents pass validation against their DTDs:
$ python val.py order.xml
Neue Elementtyp-Deklaration: customer_name
Inhaltsmodell: ('', [('#PCDATA', '')], '')
Neue Elementtyp-Deklaration: sku
Inhaltsmodell: ('', [('#PCDATA', '')], '')
Neue Elementtyp-Deklaration: qty C
Inhaltsmodell: ('', [('#PCDATA', '')], '')
Neue Elementtyp-Deklaration: unit_price
Inhaltsmodell: ('', [('#PCDATA', '')], '')
Neue Elementtyp-Deklaration: product_name
Inhaltsmodell: ('', [('#PCDATA', '')], '')
Neue Elementtyp-Deklaration: order
Inhaltsmodell: (',', [('customer_name', ''), ('sku', ''), ('qty', ''),
('unit_price', ''), ('product_name', '')], '')
Ende der DTD...By supplying the XMLValidator from xmlproc with handlers, you can capture information about the document’s validity and use it as you wish. In the next section, we add validation to the test by creating a translation and validation example that runs on a web server.
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from the book "Python & XML" is subject to the same conditions as the printed edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de
back to top