2015-11-02 93 views
0

我的XML文件類似於這樣如何獲取給定python中的值的標籤名稱?

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

我想要的標籤名稱時,給出的字符串。例如,如果我指定像'|'這樣的字符串,我想要標籤,例如標題。如何在python中實現這個功能?如果|被作爲輸入,然後它打印heading

+0

你有沒有得到你的解決方案? – SIslam

回答

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 

相關問題