如何递归地获取lxml中的speceific元素和子元素?

时间:2017-06-20 09:10:51

标签: xml iterator lxml elementtree

我有这样的xml文件(当然是xml文件的一小部分)和文章内容

<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 个答案:

答案 0 :(得分: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>
...