使用字典来更改xml中的元素文本

时间:2013-06-16 02:09:39

标签: python xml dictionary iteration

我正在尝试学习python,同时也为自己节省了大量的工作。

我有一个xml文件和一个字典文件映射旧设备ID。

我正在尝试迭代树和任何与字典键匹配的logical_devid子项或者每个字典键找到相应的logical_devid。在任何一种情况下,用它的新值替换logical_devid.text。

e.g。 xml片段

<lun>
   <pseudo_dev>emcpower146a</pseudo_dev>
   <udev>0x12b00000490</udev>
   <product_id>symmetrix</product_id>
   <frame_id>000192604705</frame_id>
   <logical_devid_type>symm_id</logical_devid_type>
   <logical_devid>0A43</logical_devid>
 </lun>

的文本文件
0A40   0127
0A41   0128
0A42   0129
0A43   012A

我已将xml文件作为ElementTree对象加载,并将文本文件加载到字典中。

import xml.etree.cElementTree as ET
tree = ET.ElementTree(file='emcpower.mappings')
d = {}
with open("translate-table.txt") as f: 
    for line in f: 
        (old, new) = line.split() 
        d[(old)] = new

我一直试图找出迭代和替换elem.text的最佳方法 我认为最好的方法是迭代字典中的已知更改。

for old_devid, new_devid in d.iteritems():

然后为与logical_devid匹配的子逻辑_devid执行某种xml查找,将elem.text设置为new_devid

这是完整的脚本,几乎可以满足我的需求:
    #!的/ usr / bin中/ Python的

try:
        import xml.etree.cElementTree as ET
except ImportError:
        import xml.etree.ElementTree as ET

#read in emcpower.mappings file as an entire xml tree of elements
tree = ET.ElementTree(file='emcpower.mappings')

# this defines a dictionary with the contents of the translate table which
# is simply the old device ID as key and new device id as value

d = {}
with open("translate-table.txt") as f:
        for line in f:
                (old, new) = line.split()
                d[(old)] = new

for elem in tree.iterfind('lun/logical_devid'):
        old_devid = elem.text
        new_devid = d.get(old_devid)
        try:
                new_devid
        except NameError:
                new_devid = None
        else:
                if new_devid:
                        elem.text = new_devid
                        print "The logical_devid will be changed to", elem.text



tree.write('emcpower.mappings.new', )

1 个答案:

答案 0 :(得分:0)

我认为迭代tree并查看每个logical_devid是否在d更有意义。在变量(例如logical_devid)中有old_devid后,则:

new_devid = d.get(old_devid)

将查看您是否有替代品。如果new_devid is null那么它不在字典中。否则,new_devid应替换树中logical_devid的当前值。