JT3
JT3

Reputation: 1

ElementTree Replace Tag Attribute and Update File

I am trying to clean an XML file by replacing tag attributes with the correct value.

When I run my code below, the tag attribute is updated but only in the Element Tree tag object, the XML file is not being updated/saved.

Is there a way to update/save the changes made to the XML objects while within ET.iterparse? Is there a way to update the file after I have changed all the tag attribute values within my loop?

When I print out tag.attrib['v'] before and after the change, it is correctly updated with the correct value. But my saved XML file does not reflect these changes.

All the solutions I have found do not making use of ET.iterparse method. I am working with a rather large file and would like to maintain my usage of ET.iterparse.

Using:

Thanks.

def writeClean(self, cleaned_streets):
    '''
    Get cleaned streets mapping dictionary and use that dictionary to find
    and replace all bad street name tag attributes within XML file.

    Iterate through XML file to find all bad instances of tag attribute 
    street names, and replace with correct mapping value from cleaned_streets
    mapping dictionary.

    '''
    with open(self.getSampleFile(), 'r+') as f:            
        for event, elem in ET.iterparse(f, events=('start',)):
            if elem.tag == 'node' or elem.tag == 'way':
                for tag in elem.iter('tag'):
                    if self.isStreetName(tag):
                        street = tag.attrib['v']
                        if street in cleaned_streets.keys():
                            tag.attrib['v'] = cleaned_streets[street]

Upvotes: 0

Views: 3053

Answers (1)

al27091
al27091

Reputation: 111

Using ElemetTree you can do:

  tree = ET.parse(file_path)
  # Do some modification to your file
  tree.write(file_path)

For example I have a piece of code that is like:

 def __update_cfg_file(self):
   try:
        tree = ET.parse(self._config_file_path)
        root = tree.getroot()
        add_file_element = "./input/additional-files"

        root.find(add_file_element).attrib["value"] = "additional-files"

        tree.write(self._config_file_path)

    except IOError:
        sys.exit("Something went wrong while opening %s"
                 % (self._config_file_path))

Upvotes: 1

Related Questions