本文介绍了获取元素的属性及其对应的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这个xml文件:
suppose that i have this xml file :
<article-set xmlns:ns0="http://casfwcewf.xsd" format-version="5">
<article>
<article id="11234">
<source>
<hostname>some hostname for 11234</hostname>
</source>
<feed>
<type weight=0.32>RSS</type>
</feed>
<uri>some uri for 11234</uri>
</article>
<article id="63563">
<source>
<hostname>some hostname for 63563 </hostname>
</source>
<feed>
<type weight=0.86>RSS</type>
</feed>
<uri>some uri for 63563</uri>
</article>
.
.
.
</article></article-set>
我想要的是在整个文档的RSS中打印每个具有其特定属性权重的文章ID(像这样).
what I want, is to print each article id with its specific attribute weight in RSS for the whole document (like this).
id=11234
weight= 0.32
id=63563
weight= 0.86
.
.
.
我用这段代码来做到这一点,
I used this code to do so,
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')
for weight in tree.xpath("//article[@id={}]/feed/type/@weight".format(article_id)):
print(article_id,weight)
它没有用,有人可以帮我吗?
and it did not work, could someone help me with this?
推荐答案
如果您确实想这样做,可以分两行进行 .
You can do it in two lines if you really want to do so.
>>> from lxml import etree
>>> tree = etree.parse('public.xml')
>>> for item in tree.xpath('.//article[@id]//type[@weight]'):
... item.xpath('../..')[0].attrib['id'], item.attrib['weight']
...
('11234', '0.32')
('63563', '0.86')
我使用的一个xml检查器坚持将weight
的值括在双引号中. etree
在xml上发出嘶哑的声音,直到我将文件的第一行删除为止.我不知道为什么.
One xml checker I used insisted on double-quotes around the values for weight
. etree
croaked on the xml until I dropped the first line in the file; I don't know why.
这篇关于获取元素的属性及其对应的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!