के साथ विशेषता द्वारा तत्व ढूंढना मुझे कुछ डेटा निकालने के लिए एक 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>
यहाँ मैं प्रकार "समाचार" के साथ ही लेख प्राप्त करना चाहते हैं: मैं केवल कुछ विशेषताओं के साथ कुछ तत्वों की जरूरत है, यहाँ दस्तावेज़ का एक उदाहरण है। एलएक्सएमएल के साथ ऐसा करने का सबसे कुशल और सुरुचिपूर्ण तरीका क्या है?
मुझे लगता विधि के साथ की कोशिश की लेकिन यह बहुत अच्छा नहीं है:
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