element_tree_object.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. # -*- coding: utf-8 -*-
  2. import xml.etree.ElementTree as et
  3. class MissingChildOrAttribute(Exception):
  4. def __init__(self, *args, **kwargs):
  5. super(MissingChildOrAttribute, self).__init__(*args, **kwargs)
  6. class EtObject:
  7. def __init__(self, element=None, file_path=None):
  8. if element is not None:
  9. self.element = element
  10. elif file_path is not None:
  11. self.tree = et.parse(file_path)
  12. self.element = self.tree.getroot()
  13. def __getattr__(self, name):
  14. childs = self.element.findall(name)
  15. objects = [EtObject(c) for c in childs]
  16. if len(objects) == 0:
  17. if not name in self.element.attrib:
  18. raise MissingChildOrAttribute(name)
  19. return self.element.attrib[name]
  20. else:
  21. return objects
  22. def __repr__(self):
  23. return et.tostring(self.element)
  24. def __str__(self):
  25. return self.__repr__()
  26. def save(self, file_name):
  27. self.tree.write(file_name)