繁体   English   中英

ElementTree查找子元素的索引

[英]ElementTree find index of SubElement

我正在尝试使用python编辑XML格式的.plist文件。 在此示例中,我要修改IP地址。

<dict>
    <key>ProgramArguments</key>
    <array>
        <string>/Applications/ExD2017/render/bin/renderqueue</string>
        <string>-h</string>
        <string>127.0.0.1</string>
    </array>
</dict>

在这种情况下,我可以使用root[1][2].text来获取值,但是如果XML中的参数顺序发生变化,这将中断。 因此,我需要通过在名为string的标签之后指定标签来找到它,其值为-h 如何找到值为-h的字符串的索引? 它应该是像root[x][x]这样的嵌套数字。

由于您仍然必须遍历所有子级,因此要找到-h ,可以简单地遍历下一个子级:

h_found = False
for child in array_element:
    if child.text == '-h':
        h_found = True
    elif h_found:
        child.text = new_ip
        break

暂无
暂无

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

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