One possible way to remove a namespace prefix from each element is:
def strip_ns_prefix(tree): #iterate through only element nodes (skip comment node, text node, etc) : for element in tree.xpath('descendant-or-self::*'): #if element has prefix... if element.prefix: #replace element name with its local name element.tag = etree.QName(element).localname return tree
Another version that checks the namespace in xpath instead of using the if :
def strip_ns_prefix(tree): #xpath query for selecting all element nodes in namespace query = "descendant-or-self::*[namespace-uri()!='']" #for each element returned by the above xpath query... for element in tree.xpath(query): #replace element name with its local name element.tag = etree.QName(element).localname return tree
har07 source share