简体   繁体   English

如何使用python计算xml特定元素编号?

[英]how to count xml specific element numbers using python?

Hi I'm trying to know how to count specific element numbers in XML using python. 嗨,我想知道如何使用python计算XML中的特定元素编号。 please see example as following 请参见以下示例

If i wanted to count number of BBB under the first AAA what would i do ? 如果我想根据第一个AAA计算BBB的数量,该怎么办? There are 3 BBB under the first AAA as you can see. 如您所见,第一个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>

and this is my code to count those. 这是我的代码来计算这些。

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)

but it doesn't count even though no error. 但即使没有错误也不算在内。 What's wrong? 怎么了? i need some advice please. 我需要一些建议。

Using ElementTree 使用ElementTree

Demo: 演示:

import xml.etree.ElementTree as ET
doc = ET.fromstring(data)

for AAA in doc.findall('AAA'):
    print len(AAA.findall('CCC'))

Output: 输出:

3
1
2

This works for me: 这对我有用:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM