有一个如下所示的xml文件:
<hh>
<aa>
<cc>
<ee>
<Name>John</Name>
</ee>
<cc>
<ee>
<Name>David</Name>
</ee>
</aa>
<bb>
<dd>
<Name>John</Name>
</dd>
<dd>
<Name>David</Name>
</dd>
</bb>
</hh>
我正在尝试修改名称: “约翰->玫瑰”和“大卫->吉娜”
所以我写如下代码:
import xml.etree.ElementTree as ET
import glob
for file in glob.glob("ff/*.xml"):
tree = ET.parse(file)
root = tree.getroot()
a01 = "aa/cc[1]/ee"
a02 = "bb/dd[1]"
b01 = "aa/cc[2]/ee"
b02 = "bb/dd[2]"
apaths = [a01, a02]
bpaths = [b01, b02]
for i in apaths:
aa = root.findall(apaths)
aa.text = "Rose"
tree.write(file)
for i in bpaths:
bb = root.findall(bpaths)
bb.text = "Gina"
tree.write(file)
但是它会响应“ TypeError:不可散列的类型:'list'”。有人可以帮助我更正我的代码吗? 非常感谢。
答案 0 :(得分:1)
这是完整的工作代码
已更新,符合新要求
import xml.etree.ElementTree as ET
import glob
for file in glob.glob("ff/*.xml"):
tree = ET.parse(file)
root = tree.getroot()
for name in root.findall('.//aa//Name'):
name.text = 'Rose'
for name in root.findall('.//bb//Name'):
name.text = 'Gina'
tree.write(file)
更新的代码以对目录中的所有xml文件进行操作
import xml.etree.ElementTree as ET
import glob
name_map = {
'John': 'Rose',
'David': 'Gina',
}
for file in glob.glob("ff/*.xml"):
tree = ET.parse(file)
root = tree.getroot()
for name in root.findall('.//Name'):
new_name = name_map.get(name.text)
if new_name:
name.text = new_name
tree.write(file)
import xml.etree.ElementTree as ET
xml_str = '''
<hh>
<aa>
<cc>
<ee>
<Name>John</Name>
</ee>
</cc>
<ee>
<Name>David</Name>
</ee>
</aa>
<bb>
<dd>
<Name>John</Name>
</dd>
<dd>
<Name>David</Name>
</dd>
</bb>
</hh>
'''
name_map = {
'John': 'Rose',
'David': 'Gina',
}
xml = ET.fromstring(xml_str)
print(ET.tostring(xml))
for name in xml.findall('.//Name'):
new_name = name_map.get(name.text)
if new_name:
name.text = new_name
print(ET.tostring(xml))
答案 1 :(得分:0)
您正在使用list参数调用Element.findall,而是:
for i in apaths:
aa = root.findall(i)
aa[0].text = "Rose"
和
for i in bpaths:
bb = root.findall(i)
bb[0].text = "Gina"