Skip to content

Instantly share code, notes, and snippets.

@nenodias
Created January 26, 2024 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nenodias/def716457bfcf6e6cc97e1cf2f0ddad7 to your computer and use it in GitHub Desktop.
Save nenodias/def716457bfcf6e6cc97e1cf2f0ddad7 to your computer and use it in GitHub Desktop.
Altera attributo de xml com python3

Para executar o script é necessário o python3 instalado e configurado no PATH.

python3 altera_xml.py arquivo.xml
import sys
import pdb
import xml.etree.ElementTree as ET
def processar_xml(filename, fn):
mytree = ET.parse(filename)
mytree = fn(mytree)
mytree.write(filename)
return True
def altera_xml(root):
for name_tag in root.findall("./food/name"):
print(name_tag.text)
#name_tag.attrib.pop('itemid')
name_tag.set("itemid", "1")
print(name_tag.attrib)
return root
if __name__ == "__main__":
filename = sys.argv[1]
processar_xml(filename, altera_xml)
<breakfast_menu>
<food>
<name itemid="1">Belgian Waffles</name>
<price>5.95</price>
<description>Two of our famous Belgian Waffles
with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name itemid="2">Strawberry Belgian Waffles</name>
<price>7.95</price>
<description>Light Belgian waffles covered
with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name itemid="3">Berry-Berry Belgian Waffles</name>
<price>8.95</price>
<description>Light Belgian waffles covered with
an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name itemid="4">French Toast</name>
<price>4.50</price>
<description>Thick slices made from our
homemade sourdough bread</description>
<calories>600</calories>
</food>
</breakfast_menu>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment