4 def __init__(self, root_node, namespaces = None):
5 self.root_node = root_node
6 self.namespaces = namespaces
8 def xpath(self, xpath):
9 return this.root_node.xpath(xpath, namespaces=self.namespaces)
11 def add_element(self, name, attrs={}, parent=None, text=""):
13 Generic wrapper around etree.SubElement(). Adds an element to
14 specified parent node. Adds element to root node is parent is
18 parent = self.root_node
19 element = etree.SubElement(parent, name)
22 if isinstance(attrs, dict):
24 element.set(attr, attrs[attr])
27 def remove_element(self, element_name, root_node = None):
29 Removes all occurences of an element from the tree. Start at
30 specified root_node if specified, otherwise start at tree's root.
33 root_node = self.root_node
35 if not element_name.startswith('//'):
36 element_name = '//' + element_name
38 elements = root_node.xpath('%s ' % element_name, namespaces=self.namespaces)
39 for element in elements:
40 parent = element.getparent()
41 parent.remove(element)
44 def add_attribute(self, elem, name, value):
46 Add attribute to specified etree element
48 opt = etree.SubElement(elem, name)
51 def remove_attribute(self, elem, name, value):
53 Removes an attribute from an element
56 opts = elem.iterfind(name)
62 def get_attributes(self, elem=None, depth=None):
65 attrs = dict(elem.attrib)
66 attrs['text'] = str(elem.text).strip()
67 if depth is None or isinstance(depth, int) and depth > 0:
68 for child_elem in list(elem):
69 key = str(child_elem.tag)
71 attrs[key] = [self.get_attributes(child_elem, recursive)]
73 attrs[key].append(self.get_attributes(child_elem, recursive))
76 def attributes_list(self, elem):
77 # convert a list of attribute tags into list of tuples
78 # (tagnme, text_value)
82 opts.append((e.tag, e.text))