2017-06-20 108 views
1

我有這樣的XML文件,該文件是這個樣子(當然它的XML文件的一小部分)和文章ID如何在lxml中遞歸地獲取特定元素和子元素?

<article-set xmlns:ns0="http://casfwcewf.xsd" format-version="5"> 
<article> 
<article id="11234"> 
    <source> 
    <hostname>some hostname for 11234</hostname> 
    </source> 
    <feed> 
     <type>RSS</type> 
    </feed> 
    <uri>some uri for 11234</uri> 
</article> 
<article id="63563"> 
    <source> 
    <hostname>some hostname for 63563 </hostname> 
    </source> 
    <feed> 
     <type>RSS</type> 
    </feed> 
    <uri>some uri for 63563</uri> 
    </article> 
. 
. 
. 
</article></article-set> 

我想要什麼,是打印每篇文章ID具有其特定的主機名和URI的整個文件(像這樣)。

id=11234 
uri= some uri for 11234 
source=some hostname for 11234 

id=63563 
uri= some uri for 63563 
source=some hostname for 63563 
. 
. 
. 

我用這個代碼,這樣做,

from lxml import etree 
tree = etree.parse("C:\\Users\\me\\Desktop\\public.xml") 

for article in tree.iter('article'): 

    article_id=article.attrib.get('id') 
    uri= tree.xpath("//article[@id]/uri/text()") 
    source= tree.xpath("//article[@id]/source/hostname/text()") 

    #i even used these two codes 
    #source=article.attrib.get('hostname') 
    #source = etree.SubElement(article, "hostname") 



    print('id={!s}'.format(article_id),"\n") 
    print('uri={!s}'.format(uri),"\n") 
    print('source={!s}'.format(source),"\n") 

,並沒有工作,可能有人幫助我?

回答

1

有可能是一些更聰明的寫作方式,然而,這似乎工作。

>>> for article in tree.iter('article'): 
...  article_id = article.attrib.get('id') 
...  uri = tree.xpath("//article[@id={}]/uri/text()".format(article_id)) 
...  source = tree.xpath("//article[@id={}]/source/hostname/text()".format(article_id)) 
...  article_id, uri, source 
...  
('11234', ['some uri for 11234'], ['some hostname for 11234']) 
('63563', ['some uri for 63563'], ['some hostname for 63563 ']) 

順便提及我改變的XML使剛剛所述容器元素中的元素是<articles>(而非<article>)。像這樣:

<article-set xmlns:ns0="http://casfwcewf.xsd" format-version="5"> 
<articles> 
<article id="11234"> 
    <source> 
... 
+0

謝謝@Bill Bell它工作完美 –

+0

非常歡迎您。 –

+0

我還有另一個問題,如果你能回答,我會很感激。現在假設在我們的例子中像''這樣的元素也有一個屬性,並且我們希望捕獲與其id相對應的屬性(對於每個文章ID)。你會怎麼做? –