【问题标题】:ElementTree find index of SubElementElementTree 查找 SubElement 的索引
【发布时间】:2018-03-28 08:01:56
【问题描述】:

我正在尝试使用 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 中的参数顺序发生更改,这将中断。所以我需要通过在名为字符串的标签后面指定标签来找到它,其值为-h。如何找到值为-h 的字符串的索引?它应该是像root[x][x] 这样的嵌套数字。

【问题讨论】:

  • 您想查看 XPath (docs.python.org/3.6/library/…)。在 99% 的情况下,尝试对 XML 树使用数字索引是错误的做法。这是其中一种情况。
  • 谢谢。你知道如何用 XPath 做到这一点吗?根据在线 XPath 测试器的说法,这段代码应该可以工作,但它在我的脚本中给出了语法错误。 root.findall("./dict/array/string[.='-h']")
  • 嗯,elementtree 的 XPath 实现很乏味。 ./dict/array[string='-h'](“通过其中一个子元素的文本值查找元素”)可以工作,不支持./dict/array/string[.='-h'](“通过其自己的文本值查找元素”)。还有see here。您是否有任何机会安装了 lxml,那里的事情会更加直接:tree.xpath("./dict/array/string[preceding-sibling::string[1]='-h']") 会为您提供正确的元素。

标签: python xml plist elementtree


【解决方案1】:

既然你无论如何都要遍历所有的孩子,要找到-h,你可以简单地迭代到下一个孩子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    相关资源
    最近更新 更多