Save modified XML from code with python

0

I have an xml where I modified the data of a specific tag. Now I just want to save the xml so that it is modified. I hardly know about python, so any advice, welcome. This was the code I used to modify the tag:

from lxml import etree

doc = etree.parse('archivo.XML')
etiqueta_raiz = doc.getroot()
for etiqueta_secundaria in etiqueta_raiz:
    for item in etiqueta_secundaria:
        monto = float(etiqueta_secundaria[6].text) / 100000
    monto = str(monto)
    etiqueta_secundaria[6].text = monto
    print etiqueta_secundaria[6].text
    
asked by DDBCDVD 06.09.2018 в 20:00
source

1 answer

0

There are several ways to do that one is using the methods of accessing files for example.

#!/usr/bin/python

# Open a file
fo = open("test.xml", "wb")
print "<newtag value='x'> </tag>"

# Close opend file
fo.close()

Another using a library that allows you to have an interface to read and write xml files, for example ElementTree

import xml.etree.ElementTree

et = xml.etree.ElementTree.parse('text')

# Agregar nueva etiqueta <a x='1' y='abc'>body</a>
new_tag = xml.etree.ElementTree.SubElement(et.getroot(), 'a')
new_tag.text = 'body'
new_tag.attrib['x'] = '1' 
new_tag.attrib['y'] = 'abc'

#  Guardar en el archivo final
et.write('file_new.xml')
    
answered by 06.09.2018 / 20:27
source