¿cómo eliminar el atributo de un elemento etree?


He Elemento de etree tener algunos atributos - ¿cómo podemos eliminar el atributo de particular etree Elemento.

Author: Deduplicator, 2010-04-27

3 answers

El .attrib miembro del elemento objeto contiene el dict de atributos - puede utilizar .pop("key") o del como lo haría en cualquier otro dict para eliminar un par key-val.

 29
Author: Amber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-27 10:34:45

Ejemplo :

>>> from lxml import etree 
>>> from lxml.builder import E
>>> otree = E.div()
>>> otree.set("id","123")
>>> otree.set("data","321")
>>> etree.tostring(otree)
'<div id="123" data="321"/>'
>>> del otree.attrib["data"]
>>> etree.tostring(otree)
'<div id="123"/>'

Tenga cuidado a veces usted no tiene el atributo:

Siempre se sugiere que manejemos las excepciones.

try:
    del myElement.attrib["myAttr"]
except KeyError:
    pass
 6
Author: macm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-31 11:28:11

No necesita try/except mientras está haciendo estallar una tecla que no está disponible. Así es como puedes hacer esto.

Código

import xml.etree.ElementTree as ET

tree = ET.parse(file_path)
root = tree.getroot()      

print(root.attrib)  # {'xyz': '123'}

root.attrib.pop("xyz", None)  # None is to not raise an exception if xyz does not exist

print(root.attrib)  # {}

ET.tostring(root)
'<urlset> <url> <changefreq>daily</changefreq> <loc>http://www.example.com</loc></url></urlset>'
 3
Author: Clayton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-12 10:58:09