简体   繁体   English

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

[英]Replacing attributes according to tag name on xml using elementtree and python

I have xml file 我有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>

I need to find all country tags check the text with the current position of my list of countries if they are not the same we replace the country name by the right name from my list. 我需要查找所有国家/地区标签,如果文本与我所在国家/地区的当前位置不同,请检查该文本,我们将国家/地区名称替换为列表中的正确名称。 It should also create a log.txt file (this part is ok). 它还应该创建一个log.txt文件(这是可以的)。 For example, some names are not in order (Panama's neighbors are not Austri and Switzerland) so they need to be replaced and this is a long xml so I want to write a script that will do it automatically. 例如,某些名称不正确(巴拿马的邻居不是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)

I know I can replace text on xml file this way. 我知道我可以用这种方式替换xml文件上的文本。

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

However when I pass a list (righ_data[] and child.text) as arguments it does not like it and it gives me the error described above. 但是,当我将列表(righ_data []和child.text)作为参数传递时,它不喜欢它,并且给了我上述错误。

I stopped using find() method. 我停止使用find()方法。 See below for how I solved the problem. 请参阅以下有关我如何解决问题的信息。 Key and val are my dictionary. 键和值是我的字典。

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

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

This will find the tag, check that it is the right tag and modify it accordingly. 这将找到标签,检查它是否正确,然后进行相应的修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Python和libxml2根据xml中的标记属性匹配兄弟 - matching siblings according to tag attributes in xml using Python and libxml2 是否要使用python elementtree删除XML中具有相同标签名称的多个标签? - Want to delete multiple tags with same tag name in XML using python elementtree? Python XML ElementTree标记通配符 - Python XML ElementTree tag wildcard 使用python,elementtree,xml解析器获取由于某些原因而无法使用的属性? - Using python, elementtree, xml parser to get attributes not working for some reason? XML Python使用ElementTree选择众多属性中的一个 - XML Python Choosing one of numerous attributes using ElementTree 如何使用ElementTree解析python中的XML(查找标签的内容) - How to parse XML in python using ElementTree (find content of a tag) 如何使用 python ElementTree 获取 XML 中的兄弟标签值 - How to get sibling tag values in XML using python ElementTree 在python 2.6中使用ElementTree删除xml标记中的空格 - Remove Whitespaces in an xml tag using ElementTree in python 2.6 使用 python 的 ElementTree 组合文本和 xml 标签 - Combine text and xml tag using python's ElementTree 如何使用 ElementTree 通过标签参数更改 python 中 xml 文件的 2 个子元素? - How to alter 2 subelements of xml file in python by their tag parameter using ElementTree?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM