0

I'm able to print it out to the console, and it is the way I want it, but I can't seem to grasp on how to save it. The XML from the sample doesn't change. I'm using fairly big XML files and the iterparse function, as I believe is crucial.

My code:

def xmlTagMethod(xmlfile, changetag):
    tree = ET.ElementTree(file=xmlfile)
    root = tree.getroot()
    for event, elem in ET.iterparse(xmlfile):
        if event == 'end':
            if elem.tag == changetag:
                elem.set('maxwidth', '20')
        print elem.attrib
    tree.write("outPutTagData.xml")
n0win0u
  • 35
  • 7

1 Answers1

0

You are not making any changes to tree, so when you write it it will be the same as before.

You are simply modifying the event and elem elements of the iterator returned by ET.iterparse(xmlfile), which is a completely separate object from tree.

For a simpler approach you could try:

import xml.etree.ElementTree as ET
def xmlTagMethod(xmlfile, changetag):
    tree = ET.ElementTree(file=xmlfile)
    for e in tree.findall(changetag):
        e.set('maxwidth','20')
tree.write("outPutTagData.xml")
Imran
  • 12,950
  • 8
  • 64
  • 79
  • well it doesn't really matter if I print it into the console or into the file. I need the whole XML file, with updated attributes. I'm not sure though, how is that possible. The best way to do it would be to update only the tags somewhere in the for cycles and save with the rest that is unchanged. I'd like it to be as fast as possible (currently testing on 800 same tag (changetag)) and I'm not sure how to do so. – n0win0u Feb 04 '15 at 09:24
  • well this is something similar to what I am doing, it doesn't update the xml, or does it, for you? (it's not working with my xml at least) – n0win0u Feb 04 '15 at 09:47