简体   繁体   中英

ElementTree find index of SubElement

I am trying to use python to edit .plist files, which are in XML format. In this example, I want to modify the IP address.

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

In this case, I can get the value by using root[1][2].text , but this will break if the argument order in the XML changes. So I need to find it by specifying the tag following the tag named string whose value is -h . How can I find the index of the string whose value is -h ? It should be a nested number like root[x][x] .

Since you have to iterate through all children anyway, to find -h , you can you can simply iterate to the next child:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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