2017-06-20 112 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)。你会怎么做? –