如何在python中获取给定值的标记名称?

时间:2015-11-02 11:07:34

标签: python xml elementtree minidom

我的xml文件与此

类似
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder|Remind|Remain</heading>
<body>Don't forget me this weekend!</body>
</note>

我想要一个字符串给出时的标签名称。例如,如果我指定字符串'|',我想要标签,即标题。我如何在python中实现这一点?

1 个答案:

答案 0 :(得分:1)

更简单的尝试可能是 -

import lxml.etree as et

s="""
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder|Remind|Remain</heading>
<body>Don't forget me this weekend!</body>
</note>
"""

tree = et.fromstring(s)

print tree.text
query = r'%s'%raw_input("Enter text: ")

pth = r'''//*[contains(text(),'%s')]'''%query

for t in tree.xpath(pth):
    print t.tag

如果输入|,则会打印heading