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