2015-05-14 37 views
5

Sulla scia Removing child elements in XML using python ...Come posso rimuovere spazi dei nomi da un albero lxml?

Grazie a @Tichodroma, ho questo codice:

Se è possibile utilizzare lxml, provate questo:

import lxml.etree 

tree = lxml.etree.parse("leg.xml") 
for dog in tree.xpath("//Leg1:Dog", 
         namespaces={"Leg1": "http://what.not"}): 
    parent = dog.xpath("..")[0] 
    parent.remove(dog) 
    parent.text = None 
tree.write("leg.out.xml") 

Ora leg.out.xml assomiglia a questo:

<?xml version="1.0"?> 
<Leg1:MOR xmlns:Leg1="http://what.not" oCount="7"> 
    <Leg1:Order> 
    <Leg1:CTemp id="FO"> 
     <Leg1:Group bNum="001" cCount="4"/> 
     <Leg1:Group bNum="002" cCount="4"/> 
    </Leg1:CTemp> 
    <Leg1:CTemp id="GO"> 
     <Leg1:Group bNum="001" cCount="4"/> 
     <Leg1:Group bNum="002" cCount="4"/> 
    </Leg1:CTemp> 
    </Leg1:Order> 
</Leg1:MOR> 

Come modificare il mio codice per rimuovere il nome Leg1: spazio prefisso da tutti i nomi dei tag degli elementi?

+0

Ho dato un'occhiata e non ho potuto farlo funzionare. – LCGA

+1

Possibile duplicato di [Rimuovi spazio dei nomi e prefisso da xml in python usando lxml] (https://stackoverflow.com/questions/18159221/remove-namespace-and-prefix-from-xml-in-python-using-lxml) –

risposta

6

Un possibile modo per rimuovere prefisso namespace da ciascun elemento:

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 

Un'altra versione che ha namespace registrazione il xpath invece di utilizzare la dichiarazione 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 
+2

Grazie funziona perfettamente. Si adatta perfettamente anche ai miei metodi. – LCGA

+2

Potrebbe anche essere necessario chiamare 'etree.cleanup_namespaces (tree)' altrimenti 'etree.tostring (tree) 'mostrerà ancora namespace. – marbu

+2

Il secondo metodo è più robusto (per gli spazi dei nomi predefiniti) –

2

La seguente funzione può essere utilizzata per togliere namespace da un lxml albero:

def strip_ns(tree): 
    for node in tree.iter(): 
     try: 
      has_namespace = node.tag.startswith('{') 
     except AttributeError: 
      continue # node.tag is not a string (node is a comment or similar) 
     if has_namespace: 
      node.tag = node.tag.split('}', 1)[1] 
+0

l'analisi manuale delle stringhe non è una buona idea. –