2011-02-23 13 views
34

いくつかのデータを抽出するために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 

答えて

55

あなたはXPathを使用することができ、例えばroot.xpath("//article[@type='news']")

このxpath式は、値が "news"の "type"属性を持つすべての<article/>要素のリストを返します。その後、それを繰り返して、あなたが望むことをやり遂げることができます。

root = etree.fromstring(""" 
<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> 
""") 

print root.xpath("//article[@type='news']/content/text()") 

をし、この意志出力['some text', 'some text']

は単なるテキストコンテンツを取得するには、そのようにXPathを拡張することができます。または、コンテンツ要素が必要な場合は、"//article[@type='news']/content"などとなります。

7

ただ、参考のために、あなたはfindallと同じ結果を得ることができます。

root = etree.fromstring(""" 
<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> 
""") 

articles = root.find("articles") 
article_list = articles.findall("article[@type='news']/content") 
for a in article_list: 
    print a.text 
関連する問題