如何使用Python中的ElementTree中的Findall从XML文档中检索标签数



我已经阅读了堆栈上的一些响应,并试图解决此问题一段时间。

我希望能够输出:

  • 具有相同标签的元素数量(例如foo,bar和type)
  • 属性中的数字(例如Foobar)

样本预期输出(或任何变化:

foo, 1
bar, 2
type, 8
foobar, 10
foobar, 20

我正在不使用rootchild节点方法而尝试这样做。

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>]

很高兴进一步澄清。感谢任何帮助指出我的错误和错误。谢谢。

,因此您可以使用以下代码之类的内容并计算外观,以下面的代码为例。

  from xml.dom import minidom
  fname = 'library4.xml'
  xmldoc = minidom.parse('library4.xml') 
  print("type " + str(len(xmldoc.getElementsByTagName('type'))))
  print("foo " + str(len(xmldoc.getElementsByTagName('foo'))))
  print("bar " + str(len(xmldoc.getElementsByTagName('bar'))))

,其输出如下:

  type 8
  foo 1
  bar 2

最新更新