我需要解析一個xml文件來提取一些數據。 我只需要具有某些屬性的一些元素,這裏的文檔的示例:用lxml查找元素的屬性
<root>
<articles>
<article type="news">
<content>some text</content>
</article>
<article type="info">
<content>some text</content>
</article>
<article type="news">
<content>some text</content>
</article>
</articles>
</root>
在這裏,我想獲得僅與類型「新聞」的文章。 什麼是最有效和優雅的方式來做到這一點與lxml?
我試圖與find方法,但它是不是很漂亮:
from lxml import etree
f = etree.parse("myfile")
root = f.getroot()
articles = root.getchildren()[0]
article_list = articles.findall('article')
for article in article_list:
if "type" in article.keys():
if article.attrib['type'] == 'news':
content = article.find('content')
content = content.text