简体   繁体   中英

count number of related elements in xml file

I have a xml file with this structure:

<?DOMParser ?> 
<logbook:LogBook xmlns:logbook="http://www/logbook/1.0"  version="1.2">
<product>
    <serialNumber value="764000606"/>
</product>
<visits>
<visit>
    <general>
        <startDateTime>2014-01-10T12:22:39.166Z</startDateTime>
        <endDateTime>2014-03-11T13:51:31.480Z</endDateTime>
    </general>
    <parts>
        <part number="03081" name="WSSA" index="0016"/>
    </parts>
</visit>
<visit>
<general>
    <startDateTime>2013-01-10T12:22:39.166Z</startDateTime>
    <endDateTime>2013-03-11T13:51:31.480Z</endDateTime>
</general>
<parts>
    <part number="02081" name="PSSF" index="0017"/>
    <part number="04081" name="PSRF" index="0027"/>
</parts>
</visit>
</visits>
</logbook:LogBook>

How can I get the number of parts per visit?

import xml.dom.minidom as minidom 
doc = minidom.parse('test.xml')
visitcount=len(doc.getElementsByTagName('visit'))

This gives me 2 visits, but how can I know that in each visit how many parts exist? I want to get this output : [1,2] , means that in the first visit, one part exists and in the second visit two parts exist.

Any idea?

import xml.dom.minidom as minidom 
doc = minidom.parse('test.xml')
visits = doc.getElementsByTagName('visit')
partcount = [len(visit.getElementsByTagName('part')) for visit in visits]
print(partcount)  # => [1, 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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