【问题标题】:python ElementTree - find value of child's attribute based on parent's attributepython ElementTree - 根据父属性查找子属性的值
【发布时间】:2022-01-19 11:00:52
【问题描述】:

这是我的 XML 文件中的示例。

<parent    uniqueID="1000" name="Bob Ross"   >
    <child     atrribute1="value"
</parent>

用户要搜索一个uniqueID,程序会返回各种信息。

使用元素树,我可以使用它返回父级中“名称”的值

x = root.find("./parent[@uniqueID='"+entered_text+"']").attrib['name']

我想根据用户搜索的 uniqueID 获取孩子的元素“attribute1”。我只是不知道该怎么做。

我一直在搜索和查看文档,但是我对 python 和元素树还很陌生,所以我可能错过了。

非常感谢, 大佬们

【问题讨论】:

    标签: python python-3.x xml elementtree


    【解决方案1】:

    通常我在这里发帖后会解决 - 这是任何偶然发现这个问题的人的答案

    使用 Xpath,您只需添加另一个 /,因为它已经在查看父级。

    root.find(".//parent[@uniqueID='" + entered_text + "']/child").attrib['attribute1']
    

    【讨论】:

    • 我正要这么说!很好,你想通了。您也可以使用x = root.find(".//parent[@uniqueID='" + entered_text + "']]") 获取父元素。然后可以通过索引父元素找到子元素,因此子元素将是child = x[0],您可以执行您已经做过的操作:attribute1 = child.attrib['attribute1']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多