+# a wrapper class around lxml.etree._Element
+# the reason why we need this one is because of the limitations
+# we've found in xpath to address documents with multiple namespaces defined
+# in a nutshell, we deal with xml documents that have
+# a default namespace defined (xmlns="http://default.com/") and specific prefixes defined
+# (xmlns:foo="http://foo.com")
+# according to the documentation instead of writing
+# element.xpath ( "//node/foo:subnode" )
+# we'd then need to write xpaths like
+# element.xpath ( "//{http://default.com/}node/{http://foo.com}subnode" )
+# which is a real pain..
+# So just so we can keep some reasonable programming style we need to manage the
+# namespace map that goes with the _Element (its internal .nsmap being
+# unmutable)
+
+
+class XmlElement:
+
+ def __init__(self, element, namespaces):
+ self.element = element
+ self.namespaces = namespaces
+
+ # redefine as few methods as possible
+ def xpath(self, xpath, namespaces=None):
+ if not namespaces:
+ namespaces = self.namespaces
+ elems = self.element.xpath(xpath, namespaces=namespaces)
+ return [XmlElement(elem, namespaces) for elem in elems]
+
+ def add_element(self, tagname, **kwds):
+ element = etree.SubElement(self.element, tagname, **kwds)
+ return XmlElement(element, self.namespaces)
+
+ def append(self, elem):
+ if isinstance(elem, XmlElement):
+ self.element.append(elem.element)
+ else:
+ self.element.append(elem)
+
+ def getparent(self):
+ return XmlElement(self.element.getparent(), self.namespaces)
+
+ def get_instance(self, instance_class=None, fields=None):
+ """
+ Returns an instance (dict) of this xml element. The instance
+ holds a reference to this xml element.
+ """
+ if fields is None:
+ fields = []
+ if not instance_class:
+ instance_class = Element
+ if not fields and hasattr(instance_class, 'fields'):
+ fields = instance_class.fields
+
+ if not fields:
+ instance = instance_class(self.attrib, self)
+ else:
+ instance = instance_class({}, self)
+ for field in fields:
+ if field in self.attrib:
+ instance[field] = self.attrib[field]
+ return instance
+
+ def add_instance(self, name, instance, fields=None):
+ """
+ Adds the specifed instance(s) as a child element of this xml
+ element.
+ """
+ if fields is None:
+ fields = []
+ if not fields and hasattr(instance, 'keys'):
+ fields = instance.keys()
+ elem = self.add_element(name)
+ for field in fields:
+ if field in instance and instance[field]:
+ elem.set(field, unicode(instance[field]))
+ return elem
+
+ def remove_elements(self, name):
+ """
+ Removes all occurences of an element from the tree. Start at
+ specified root_node if specified, otherwise start at tree's root.
+ """
+
+ if not element_name.startswith('//'):
+ element_name = '//' + element_name
+ elements = self.element.xpath('%s ' % name, namespaces=self.namespaces)
+ for element in elements:
+ parent = element.getparent()
+ parent.remove(element)
+
+ def delete(self):
+ parent = self.getparent()
+ parent.remove(self)
+
+ def remove(self, element):
+ if isinstance(element, XmlElement):
+ self.element.remove(element.element)
+ else:
+ self.element.remove(element)
+
+ def set_text(self, text):
+ self.element.text = text
+
+ # Element does not have unset ?!?
+ def unset(self, key):
+ del self.element.attrib[key]
+
+ def toxml(self):
+ return etree.tostring(self.element, encoding='UTF-8', pretty_print=True)
+
+ def __str__(self):
+ return self.toxml()
+
+ # other method calls or attribute access like .text or .tag or .get
+ # are redirected on self.element
+ def __getattr__(self, name):
+ if not hasattr(self.element, name):
+ raise AttributeError(name)
+ return getattr(self.element, name)
+
+