We Recommend

Learning Python Learning Python
The authors of Learning Python show you enough essentials of the Python scripting language to enable you to begin solving problems right away, then reveal more powerful aspects of the language one at a time. This approach is sure to appeal to programmers and system administrators who have urgent problems and a preference for learning by semi-guided experimentation.


Posted By

n3x on 07/18/07


Tagged

dtd xml validate PyXML


Versions (?)


XML DTD validation for python


Published in: Python 


jotham from #pygame made this module that provides 'optional' DTD validation, i.e. if the PyXML module is available, your file is checked, otherwise it does nothing.

  1. """
  2. Optional XML Validator
  3.  
  4. This module attempts to provide XML DTD validation support. This module should not cause
  5. a critical error if PyXML is not installed on the users system.
  6. """
  7.  
  8. try:
  9. from xml.parsers.xmlproc import xmlval
  10. from xml.parsers.xmlproc import xmlproc
  11. except ImportError, e:
  12. print 'Not validating, Import Error:', e
  13. ValidationError = None
  14. else:
  15. class ValidationError (Exception):
  16. def __init__ (self, type, message, location):
  17. self.type = type
  18. self.message = message
  19. self.location = location
  20. def __repr__ (self):
  21. return "L%s:%s %s: %s" % (self.location[0], self.location[1], self.type, self.message)
  22.  
  23. class ErrorHandler (xmlproc.ErrorHandler):
  24. def location (self):
  25. return self.locator.get_line(), self.locator.get_column()
  26. def warning (self, msg):
  27. raise ValidationError('Warning', msg, self.location())
  28. def error (self, msg):
  29. raise ValidationError('Error', msg, self.location())
  30. def fatal (self, msg):
  31. raise ValidationError('Fatal', msg, self.location())
  32.  
  33. def validate_dtd (file):
  34. if not ValidationError: return # return if we (are assumed to) have not loaded the xml modules
  35. parser = xmlval.XMLValidator()
  36. parser.set_error_handler(ErrorHandler(parser))
  37. parser.parse_resource(file)
  38.  
  39. if __name__ == '__main__':
  40. try:
  41. validate_dtd('./example1.xml')
  42. except ValidationError, e:
  43. print repr(e)

Report this snippet 

You need to login to post a comment.