繁体   English   中英

在 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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM