我有以下XML文件:
<main>
<node>
<party iot="00">Big</party>
<children type="me" value="3" iot="A">
<p>
<display iot="B|S">
<figure iot="FF"/>
</display>
</p>
<li iot="C"/>
<ul/>
</children>
</node>
<node>
<party iot="01">Small</party>
<children type="me" value="1" iot="N">
<p>
<display iot="T|F">
<figure iot="MM"/>
</display>
</p>
</children>
</node>
</main>如何从iot first node的children的子元素中检索属性的所有值?我需要以列表的形式检索iot的值。
预期结果:
iot_list = ['A','B|S','FF','C']这是我目前的代码:
import xml.etree.ElementTree as ET
mytree = ET.parse("file.xml")
myroot = mytree.getroot()
list_nodes = myroot.findall('node')
for n in list_nodes:
# ???发布于 2022-04-24 13:05:44
使用lxml库更容易做到这一点:
如果问题中的示例xml表示实际xml的确切结构:
from lxml import etree
data = """[your xml above]"""
doc = etree.XML(data)
print(doc.xpath('//node[1]//*[not(self::party)][@iot]/@iot'))更笼统地说:
for t in doc.xpath('//node[1]//children'):
print(t.xpath('.//descendant-or-self::*/@iot'))在任何一种情况下,输出都应该是
['A', 'B|S', 'FF', 'C']https://stackoverflow.com/questions/71917488
复制相似问题