我已经阅读了一些堆栈上的响应,并试图解决这个问题一段时间。如何从Python中的elementTree使用findall从xml文档检索标记的数量
我希望能够以输出:
- 具有相同标记的元素(比如foo,酒吧和类型)
- 属性内的数字(如foobar的)
样品预计产出(或任何变化:
foo, 1
bar, 2
type, 8
foobar, 10
foobar, 20
我试图做到这一点不使用root
和child
节点方法。
XML文档
<first>
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
<type foobar="3"/>
<type foobar="4"/>
</bar>
<bar>
<type foobar="1"/>
<type foobar="2"/>
<type foobar="3"/>
<type foobar="4"/>
</bar>
</foo>
</first>
Python代码
import xml.etree.ElementTree as ET
fname = 'Library4.xml' # handle
stuff = ET.parse(fname)
for atype in stuff.findall('type'):
print(atype.get('foobar'))
all = stuff.findall('bar')
print('bar', all)
all = stuff.findall('foo')
print('foo', all)
输出我得到:
bar []
foo [<Element 'foo' at 0x000001E3C71F8B38>]
快乐,以进一步澄清。感谢任何帮助,指出我的错误和错误。谢谢。
你能否也把你所期望的输出? –
@ChetanVasudevan是的,我编辑并澄清了我希望得到的输出。谢谢。 –