【问题标题】:how to count xml specific element numbers using python?如何使用 python 计算 xml 特定元素的数量?
【发布时间】:2018-05-23 15:54:22
【问题描述】:

您好,我想知道如何使用 python 计算 XML 中的特定元素数。 请看下面的例子

如果我想计算第一个 AAA 下的 BBB 数量,我会怎么做? 如您所见,第一个 AAA 下有 3 个 BBB。

<data>
    <AAA>  -> The first AAA
        <CCC>
            <BBB>This</BBB>
        </CCC>
        <CCC>  
            <BBB>is</BBB>
        </CCC>
        <CCC>
            <BBB>test1</BBB>
        </CCC>
    </AAA>

    <AAA>
        <CCC>
            <BBB>This is test</BBB>
        </CCC>
    </AAA>

    <AAA>
        <CCC>
            <BBB>222222</BBB>
        </CCC>
        <CCC>
            <BBB>333333</BBB>
        </CCC>      
    </AAA>

这是我计算这些的代码。

a=0

for AAA in root.findall('AAA')[a]:
    for CCC in AAA.findall('CCC'):
        for BBB in CCC.findall('BBB'):
            count = BBB.count()
            print(count)

但即使没有错误也不算数。 怎么了?请给我一些建议。

【问题讨论】:

    标签: python xml


    【解决方案1】:

    使用元素树

    演示:

    import xml.etree.ElementTree as ET
    doc = ET.fromstring(data)
    
    for AAA in doc.findall('AAA'):
        print len(AAA.findall('CCC'))
    

    输出:

    3
    1
    2
    

    【讨论】:

    • 谢谢拉克什。使用 .parse 方法时效果也很好
    【解决方案2】:

    这对我有用:

    from xml.etree import ElementTree
    
    xml_text = ElementTree.parse('your_file.xml')
    dom = xml_text.getroot()
    results = sum([1 for entry in dom.getiterator('BBB')])
    print(results)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 2015-10-08
      • 2017-04-03
      • 1970-01-01
      • 2012-02-04
      • 2016-09-01
      • 2022-10-04
      相关资源
      最近更新 更多