text
stringlengths
0
828
# Loop over children and remove empty ones directly
for parent in get_elements(element, element_path):
for child in get_elements(parent, target_element):
if element_is_empty(child):
removed.append(child)
parent.remove(child)
# Parent may be empty now: recursively remove empty elements in XPATH
if element_is_empty(parent):
if len(xpath_segments) == 2:
removed.extend(remove_empty_element(element, xpath_segments[0]))
else:
next_element_path = XPATH_DELIM.join(xpath_segments[:-2])
next_target_element = parent.tag
removed.extend(remove_empty_element(element, next_element_path, next_target_element))
return removed"
4027,"def get_elements(parent_to_parse, element_path):
""""""
:return: all elements by name from the parsed parent element.
:see: get_element(parent_to_parse, element_path)
""""""
element = get_element(parent_to_parse)
if element is None or not element_path:
return []
return element.findall(element_path)"
4028,"def get_element_attribute(elem_to_parse, attrib_name, default_value=u''):
""""""
:return: an attribute from the parsed element if it has the attribute,
otherwise the default value
""""""
element = get_element(elem_to_parse)
if element is None:
return default_value
return element.attrib.get(attrib_name, default_value)"
4029,"def get_element_attributes(parent_to_parse, element_path=None):
""""""
:return: all the attributes for the parsed element if it has any, or an empty dict
""""""
element = get_element(parent_to_parse, element_path)
return {} if element is None else element.attrib"
4030,"def set_element_attributes(elem_to_parse, **attrib_kwargs):
""""""
Adds the specified key/value pairs to the element's attributes, and
returns the updated set of attributes.
If the element already contains any of the attributes specified in
attrib_kwargs, they are updated accordingly.
""""""
element = get_element(elem_to_parse)
if element is None:
return element
if len(attrib_kwargs):
element.attrib.update(attrib_kwargs)
return element.attrib"
4031,"def remove_element_attributes(elem_to_parse, *args):
""""""
Removes the specified keys from the element's attributes, and
returns a dict containing the attributes that have been removed.
""""""
element = get_element(elem_to_parse)
if element is None:
return element
if len(args):
attribs = element.attrib
return {key: attribs.pop(key) for key in args if key in attribs}
return {}"
4032,"def get_element_tail(parent_to_parse, element_path=None, default_value=u''):
""""""
:return: text following the parsed parent element if it exists,
otherwise the default value.
:see: get_element(parent_to_parse, element_path)
""""""
parent_element = get_element(parent_to_parse, element_path)
if parent_element is None:
return default_value
if parent_element.tail:
return parent_element.tail.strip() or default_value