如何递归地获取lxml中的特定元素和子元素?
我有这样的xml文件(当然是xml文件的一小部分)和文章id如何递归地获取lxml中的特定元素和子元素?,xml,iterator,lxml,elementtree,Xml,Iterator,Lxml,Elementtree,我有这样的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>
<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>
我用了这个代码
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")
它不起作用,有人能帮我吗?很可能有更聪明的写作方法;然而,这似乎是可行的
>>> 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,使容器元素中的元素是
(而不是
)。像这样:
<article-set xmlns:ns0="http://casfwcewf.xsd" format-version="5">
<articles>
<article id="11234">
<source>
...
...
我还有一个问题,如果您能回答,我将不胜感激。现在假设在我们的示例中,像“”这样的元素也有一个属性,我们希望捕获与其id对应的该属性(对于每个项目id)。你会怎么做?请你提出另一个问题,并作更充分的解释好吗?我很难理解。举个例子可能会有所帮助。只需在这个答案上添加另一条注释,这样我就知道您何时提出了问题。获取元素的属性及其对应的Id
<article-set xmlns:ns0="http://casfwcewf.xsd" format-version="5">
<articles>
<article id="11234">
<source>
...