import lxml.etree as etree def inject(doc, add_ele, out_fufi=None): """inject an element into a document""" if(isinstance(doc, str)): ### allow for a file as the first argument parser = etree.XMLParser(remove_blank_text=True) doc = etree.parse(doc, parser) doc_root_ele = doc.getroot() doc_root_ele.append(add_ele) if out_fufi is not None: doc.write(out_fufi, pretty_print=True) return doc def show(doc, do_verbose=False): string = etree.tostring(doc, pretty_print=True).decode() if do_verbose: print(string) return string def dedup(doc, do_return=False): if(isinstance(doc, str)): ## allow for a file as the first argument parser = etree.XMLParser(remove_blank_text=True) doc = etree.parse(doc, parser) seen = {} has_it_changed = False for ele in doc.xpath('/*/*'): if 'id' not in ele.attrib: continue elid = ele.attrib['id'] if elid not in seen: seen[elid] = 1 continue ele.getparent().remove(ele) has_it_changed = True if not has_it_changed and not do_return: return None return doc