[英]Use python to determine what element(s) a value is in
我嘗試過以我能想到的所有方式進行搜索,但是沒有運氣。 如果有人用不同的方式回答了這個問題,我事先表示歉意。
我需要完成的幫助:
我有一組名稱值,例如:['John Smith','New York','Toys'],我知道它們存在於XML文檔中,例如:
<doc>
<people>
<name>John Smith</name>
</people>
<places>
<name>New York</name>
</places>
<things>
<name>Toys</name>
</things>
<about>
<name>John Smith is male.</name>
</about>
</doc>
使用elementtree,我可以遍歷列表並在文檔中找到這些值。
我想要弄清楚標題標題是怎么做的:
我無法弄清楚這一點,但我想必須有一種方法可以在不增加繁重工作的情況下完成此任務。 任何建議或建議將不勝感激。
如果您不依賴elementtree,這是一個使用lxml
的簡單示例(注意:我沒有為您做循環,您可以完成那部分工作)。 但是它將為您提供包含文本的標簽,然后是該標簽的父標簽:
#!/usr/bin/env python3
from lxml import etree
lines = None
with open('ex.xml') as f:
lines = f.read()
doc = etree.fromstring(lines)
elem = doc.xpath("//name[text()='John Smith']")
for e in elem:
parent = e.getparent()
print(parent.tag)
使用re.findall
re.findall('<name>(.*)</name>', string )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.