【问题标题】:ElementTree Replace Tag Attribute and Update FileElementTree 替换标签属性和更新文件
【发布时间】:2023-04-06 13:49:01
【问题描述】:

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

当我在下面运行我的代码时,标签属性被更新但仅在元素树标签对象中,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]

【问题讨论】:

    标签: python xml elementtree celementtree


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-01
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多