【问题标题】:How to get the tag name given the value in python? [closed]给定python中的值,如何获取标签名称? [关闭]
【发布时间】:2015-11-02 11:07:34
【问题描述】:
我的 xml 文件看起来和这个类似
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder|Remind|Remain</heading>
<body>Don't forget me this weekend!</body>
</note>
当给出一个字符串时,我想要标签名称。例如,如果我指定像 '|' 这样的字符串,我想要标签,即 heading. 如何在 python 中实现这一点?
【问题讨论】:
标签:
python
xml
elementtree
minidom
【解决方案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。