我需要解析一个XML文件来提取一些数据。
我只需要具有特定属性的一些元素,这是一个文档的示例:
<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
type
类似于imx:type
?其中imx='https://some.namespace.imx'
。 - Alex Raj Kaliamoorthyfindall
提供一个包含前缀/命名空间映射字典的namespaces
参数,例如articles.findall("article[@type='news']/content", namespaces=root.nsmap)
或者您可以手动构建它,例如namespaces={"imx": "https://some.namespace.imx"}
。 - L0tad