Tôi cần phải phân tích cú pháp tệp xml để trích xuất một số dữ liệu. tôi chỉ cần một số yếu tố với các thuộc tính nhất định, đây là một ví dụ của tài liệu:tìm các phần tử theo thuộc tính với 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>
Ở đây tôi muốn để có được chỉ là bài viết với các loại "tin tức". Cách hiệu quả nhất và thanh lịch để làm điều đó với lxml là gì?
Tôi đã thử với phương pháp tìm nhưng nó không phải là rất tốt đẹp:
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