使用elementtree和python根据标记名称在xml上替换属性

时间:2018-10-26 20:48:54

标签: python xml python-2.7 elementtree

我有xml文件

<?xml version="1.0"?>
<data>
    <country name="Panama">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Malaysia">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Liechtenstein">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

我需要找到所有国家/地区标签,如果文本不相同,请检查国家/地区列表中当前位置的文本,我们将国家/地区名称替换为列表中的正确名称。它还应该创建一个log.txt文件(这是可以的)。例如,某些名称不正确(巴拿马的邻居不是Austri和瑞士),因此需要替换它们,这是一个长xml,因此我想编写一个脚本来自动执行此操作。

import xml.etree.ElementTree as ET
import os
from xml.etree.ElementTree import SubElement

base_path = os.path.dirname(os.path.realpath(__file__))
xml_file = os.path.join(base_path, 'data.xml')
tree = ET.parse(xml_file)
root = tree.getroot()

Tags = ['country', 'rank', 'year']
right_data = ['Liechtenstein', 'Singapore', 'Panama']
# I need a log of the changes
f = open('Log.txt','w')

i =0
for tag in Tags[i:]:
    print tag
    for child in root.iter():
        print child
        if tag == child.tag:
            print 'We found matching tag %s' % tag
            if child.text != right_data[i]:
                print 'We are changing %s ' % child.text, 'to --> %s'% right_data[i]
                f.write('Changing  %s -->' % child.text)
                f.write('to name %s\n' % right_data[i])
                #This is where the problems start
                #This is supposed to find text attribute and replace it the    right_data[i] at position i
                #I get this error when I run my program
                #SyntaxError: can't assign to function call

                tree.find(child.text) = right_data[i]

        else: 
            "There is no such tag"
f.close()


new_data = ET.tostring(root)
new_xml = open('dataUpdated.xml', 'w')
new_xml.write(new_data)

我知道我可以用这种方式替换xml文件上的文本。

tree.find('Panama').text = 'Liechtenstein'
tree.write(datafile)

但是,当我将列表(righ_data []和child.text)作为参数传递时,它不喜欢它,并且给了我上述错误。

1 个答案:

答案 0 :(得分:0)

我停止使用find()方法。请参阅以下有关我如何解决问题的信息。键和值是我的字典。

customDict = {'Soap':'Dial','Shampoo':'H&S'}

for child in root.iter():
     for key, val customDict.items():
         if child.tag == key:
              child.tex = val

这将找到标签,检查它是否正确,然后进行相应的修改。