【发布时间】: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