Python—如何在XML中找到特定字符串时返回父名称

Python—如何在XML中找到特定字符串时返回父名称,python,xml,Python,Xml,我有一个xml文件,我正在搜索其中的特定字符串。找到该字符串后,我想返回它的父名称。以下是我的xml: <context> <name>AccuCapacityApp</name> <message> <source>Capacity</source> <translation type="unfinished">Kapazität</translation&

我有一个xml文件,我正在搜索其中的特定字符串。找到该字符串后,我想返回它的父名称。以下是我的xml:

<context>
    <name>AccuCapacityApp</name>
    <message>
        <source>Capacity</source>
        <translation type="unfinished">Kapazität</translation>
    </message>
    <message>
        <source>Charge Level</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Sel (Yes)</source>
        <translation type="unfinished">Sel (Ja)</translation>
    </message>
    <message>
        <source>Esc (No)</source>
        <translation type="unfinished">Esc (Nein)</translation>
    </message>
</context>

您正在使用
tree.findall('context/message')
迭代所有
message
节点,但您需要
translation
节点(它们具有
type
属性)。因此,这将作为代码的替代:

for message in tree.iterfind('.//translation[@type="unfinished"]/..'):
    print(message.attrib)
它将迭代包含子
翻译
消息
节点,其属性
type
等于
未定义
。有关更多指导,请阅读Python文档中的。请注意,我使用了更高效的
iterfind

接下来,为了实现您想要的,您需要使用
消息
,以便提取
源代码

for message in tree.iterfind('.//translation[@type="unfinished"]/..'):
    print("Source: ", message.find('source').text)
要获取
名称
标记,您需要获取
消息
的父项。那就看吧。或者只需从
tree.find('./name')
)中获取该标记即可


祝你好运。

打印源工作准确。但我试过打印
print(“Source:,tree.find('./name'))
,但它打印“None”。我已经访问了您在这里提供的链接。我不确定该遵循哪个答案
tree.find('.//b/.')
也返回“无”。投票最多的答案包含另一个for循环。我应该怎样把它和这个结合起来呢?我已经知道怎么做了。在用
parent\u map=dict((c,p)映射父对象后,我用
parent\u map[message].find('name').text打印父对象。谢谢你的帮助。
for message in tree.iterfind('.//translation[@type="unfinished"]/..'):
    print("Source: ", message.find('source').text)