ElementTree替换标记属性和更新文件

时间:2017-01-22 18:01:30

标签: python xml elementtree celementtree

我正在尝试通过使用正确的值替换标记属性来清理XML文件。

当我在下面运行我的代码时,tag属性会更新,但只在Element Tree标记对象中,XML文件没有被更新/保存。

有没有办法在ET.iterparse中更新/保存对XML对象所做的更改?在我更改了循环中的所有标记属性值后,有没有办法更新文件?

当我在更改之前和之后打印出tag.attrib ['v']时,会使用正确的值正确更新它。但是我保存的XML文件并没有反映出这些变化。

我发现的所有解决方案都没有使用ET.iterparse方法。我正在使用一个相当大的文件,并希望保持我对ET.iterparse的使用。

使用:

  • Python 2.7
  • xml.etree.cElementTree

感谢。

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]

1 个答案:

答案 0 :(得分:0)

使用ElemetTree,您可以:

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

例如,我有一段代码如下:

 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))