我正在尝试学习 python,同时也为自己节省了很多工作。
我有一个 xml 文件和一个字典文件,将旧设备 ID 映射到新设备 ID。
我正在尝试遍历树,并且对于与字典键匹配的任何logical_devid 子项,或者为每个字典键找到相应的logical_devid。在任何一种情况下,将logical_devid.text 替换为新值。
例如 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():
然后为与 old_devid 匹配的子logical_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', )