2017-01-22 10 views
0

タグ属性を正しい値に置き換えてXMLファイルを消去しようとしています。ElementTreeタグ属性と更新ファイルを置き換えます

以下のコードを実行すると、タグ属性が更新されますが、要素ツリータグオブジェクトでのみXMLファイルが更新/保存されていません。

ET.iterparse内でXMLオブジェクトに加えられた変更を更新/保存する方法はありますか?ループ内のすべてのタグ属性値を変更した後にファイルを更新する方法はありますか?

変更前と変更後にtag.attrib ['v']を出力すると、正しい値で正しく更新されます。しかし、私の保存されたXMLファイルはこれらの変更を反映していません。

私が見つけたすべての解決策は、ET.iterparseメソッドを使用していません。私はかなり大きなファイルを扱っており、ET.iterparseの使用を維持したいと考えています。

使用:

  • のPython 2.7
  • xml.etree.cElementTree

感謝を。あなたが行うことができますElemetTree

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] 

答えて

0

を使用する:

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)) 
:たとえば

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

は、私のようなコードの部分を持っています

関連する問題