【问题标题】:in python, with xml, how can I change one value only when another value exists在python中,使用xml,只有当另一个值存在时,我才能更改一个值
【发布时间】:2021-08-10 02:04:48
【问题描述】:

我有以下 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”

谢谢,

【问题讨论】:

  • 你想把&lt;tag&gt;lll&lt;/tag改成&lt;tag&gt;xxx&lt;/tag&gt;吗?

标签: python xml-parsing


【解决方案1】:
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))

【讨论】:

    猜你喜欢
    • 2022-12-11
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 2021-03-19
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多