[XML-SIG] validate and handle content at the same time.

Remy C. Cool dev-xml@smartology.nl
Fri, 20 Dec 2002 16:08:27 +0100


I still can't get the xmlproc parser to validate and process the 
content in one pass. Am I doing something wrong or can't xmlproc do 
both at the same time. 

Regards, 
Remy Cool

-- 

When  parser.setFeature(feature_validation, 1) is set ... the DTD is 
checked against the XML file but closing tags are not being printed. 
When parser.setFeature(feature_validation, 0) is set or the line is 
commented out, closing tags are printed but the xml file is not 
validated against the DTD. How can I get both ... a working 
endElement handler and DTD validation?


-- example from my previous post --

When  parser.setFeature(feature_validation, 1) is set ... the DTD is 
checked against the XML file but closing tags are not being printed. 
When parser.setFeature(feature_validation, 0) is set or the line is 
commented out, closing tags are printed but the xml file is not 
validated against the DTD. How can I get both ... a working 
endElement handler and DTD validation?

// CODE //

#!/usr/bin/python
#
# XML validator
#

import sys

from xml.sax import make_parser
from xml.sax.handler import feature_namespaces, feature_validation
from xml.sax.handler import ContentHandler, ErrorHandler, DTDHandler


class validator(ContentHandler):

   def __init__(self):
      # initialize
      self.warnings = []
      self.errors = []
      
   def endElement(self, name):
      print name

   def warning(self, exception):
      self.warnings.append(exception)

   def error(self, exception):
      self.errors.append(exception)

   def fatalError(self, exception):
      self.errors.append(exception)



if __name__ == '__main__':

   # get arguments
   arguments = sys.argv

   if len(arguments) > 1:
      xml_file = arguments[1]

      # create a parser
      parser = make_parser('xml.sax.drivers2.drv_xmlproc')
      # tell parser we are not interested in XML namespaces
      parser.setFeature(feature_namespaces, 0)
      # tell parser to enable validation
      parser.setFeature(feature_validation, 1)
      # create the handler
      valxml = validator()
      # tell the parser to use our handler
      parser.setContentHandler(valxml)
      parser.setErrorHandler(valxml)
      parser.setDTDHandler(valxml)
      # Parse the input
      parser.parse(xml_file)
                         
      # create report
      print '='*30
      print 'RESULTS: %s' % xml_file
      print '='*30
      print 'Warnings:', len(valxml.warnings)
      print 'Errors  :', len(valxml.errors)
      print

      if valxml.warnings:
         for warning in valxml.warnings:
            print 'Warning: %s' % str(warning)

      if valxml.errors:
         for error in valxml.errors:
            print 'Error  : %s' % str(error)
   else:
      # no xml file given
      print 'Usage: xml_validate.py [xml-file]'