【问题标题】:how to get speceific elements and sub elements in lxml recursively?如何递归地获取lxml中的特定元素和子元素?
【发布时间】:2017-06-20 09:10:50
【问题描述】:

我有一个这样的 xml 文件(当然它是 xml 文件的一小部分)和文章 id

<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")

它不起作用,有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: xml iterator lxml elementtree


    【解决方案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,以便容器元素内的元素是 &lt;articles&gt;(而不是 &lt;article&gt;)。像这样:

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

    【讨论】:

    • 我还有一个问题,如果您能回答,我将不胜感激。现在假设在我们的示例中,诸如“' 之类的元素也有一个属性,我们想要捕获与其 id 对应的这个属性(对于每个文章 id)。你会怎么做?
    • 能否请您提出另一个问题并更全面地解释一下?我很难理解。一个例子可能会有所帮助。只需在此答案上再发表评论,以便我知道您何时问过。
    • 获取一个元素的属性及其对应的Id stackoverflow.com/q/44710836/7427786?sem=2
    猜你喜欢
    • 2011-10-17
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多