在 python 和 xml 中,如何仅在另一个值存在时才更改一个值
in python, with xml, how can I change one value only when another value exists
我有以下 xml 文件:
<?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>
当 ABCDE/rf/src_path 为 tmp/lll
时,我需要将标签设为“xxx”
谢谢,
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))
我有以下 xml 文件:
<?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>
当 ABCDE/rf/src_path 为 tmp/lll
时,我需要将标签设为“xxx”谢谢,
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))