xml.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # coding: utf-8
  2. from _elementtree import Element
  3. from lxml import etree
  4. from synergine2.config import Config
  5. from synergine2.log import get_logger
  6. from opencombat.exception import StateLoadError
  7. class XmlValidator(object):
  8. def __init__(
  9. self,
  10. config: Config,
  11. schema_file_path: str,
  12. ) -> None:
  13. self._config = config
  14. self._logger = get_logger('XmlValidator', config)
  15. self._schema_file_path = schema_file_path
  16. def validate_and_return(self, xml_file_path: str) -> Element:
  17. with open(self._schema_file_path, 'r') as schema_file:
  18. schema_to_check = schema_file.read()
  19. # open and read xml file
  20. with open(xml_file_path, 'r') as xml_file:
  21. xml_to_check = xml_file.read()
  22. xmlschema_doc = etree.fromstring(schema_to_check.encode('utf-8'))
  23. xmlschema = etree.XMLSchema(xmlschema_doc)
  24. try:
  25. doc = etree.fromstring(xml_to_check.encode('utf-8'))
  26. # check for file IO error
  27. except IOError as exc:
  28. self._logger.error(exc)
  29. raise StateLoadError('Invalid File "{}": {}'.format(
  30. xml_file_path,
  31. str(exc),
  32. ))
  33. # check for XML syntax errors
  34. except etree.XMLSyntaxError as exc:
  35. self._logger.error(exc)
  36. raise StateLoadError('XML Syntax Error in "{}": {}'.format(
  37. xml_file_path,
  38. str(exc.error_log),
  39. ))
  40. except Exception as exc:
  41. self._logger.error(exc)
  42. raise StateLoadError('Unknown error in "{}": {}'.format(
  43. xml_file_path,
  44. str(exc),
  45. ))
  46. # validate against schema
  47. try:
  48. xmlschema.assertValid(doc)
  49. except etree.DocumentInvalid as exc:
  50. self._logger.error(exc)
  51. raise StateLoadError(
  52. 'Schema validation error in "{}": {}'.format(
  53. xml_file_path,
  54. str(exc),
  55. )
  56. )
  57. except Exception as exc:
  58. self._logger.error(exc)
  59. raise StateLoadError(
  60. 'Unknown validation error in "{}": {}'.format(
  61. xml_file_path,
  62. str(exc),
  63. )
  64. )
  65. return doc