在python中,使用xml,如何仅在存在另一个值时更改一个值
我有以下xml文件:在python中,使用xml,如何仅在存在另一个值时更改一个值,python,xml-parsing,Python,Xml Parsing,我有以下xml文件: <?xml version="1.0" encoding="UTF-8"?> <ABCDE> <global> ... </global> <rf> <r1> <type> 1 </type> <location> /root/1 <
<?xml version="1.0" encoding="UTF-8"?>
<ABCDE>
<global>
...
</global>
<rf>
<r1>
<type> 1 </type>
<location> /root/1 </location>
<tag> cloud </tag>
<src_path> tmp/ggg </src_path>
</r1>
<r1>
<type> 1 </type>
<location> /root/1 </location>
<tag>lll</tag>
<src_path> tmp/lll </src_path>
</r1>
...
1.
/根/1
云彩
tmp/ggg
1.
/根/1
微光
tmp/lll
当ABCDE/rf/src_路径为tmp/lll时,我需要标记为“xxx”
谢谢,您想更改lll吗
def update_tag(file,test_tag,new_tag):
tree=parse_xml_with_remarks(file)
root=tree.getroot()
for rf in root.findall('rf'):
for r1 in rf.findall('r1'):
src_path = r1.findall('src_path')
for sp in src_path:
src_orig = sp.text
src = sp.text.strip().split(".git")[0].replace("/", " ").split()[-1]
if src == test_tag:
# yes must repeat the tree parsing
parseTree=parse_xml_with_remarks(file)
newstr1="./rf/r1[src_path='"+src_orig+"']"
right_r1=parseTree.find(newstr1)
right_r1.find("./tag").text = new_tag
parseTree.write(file)
print ("The r1 with '{}' in the src_path tag is now using the '{}' tag tag in the file '{}'".format(test_tag,new_tag,file))
else:
print("{} is not {}, skipping file {}".format(src,test_tag,file))