2011-02-23 5 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로 가장 효율적이고 우아한 방법은 무엇입니까?

나는 찾기 방법으로 시도했지만 그것은 아주 좋은 아니에요 :

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 
관련 문제