简体   繁体   中英

How to read in every child tag and attribute from an element in xml using Python

I am trying to read in every child tag and attribute from an element in an xml file. An example of the xml is listed below.

   <drCoreType Name="default">
      <ModelType Name="default">
         <ALTrVoltage Enable="No" Group="Other" Delay="0"/>
         <ALTrCurrent Enable="Yes" Group="Minor" Delay="0"/>
         <ALTrTeAmbient Enable="Yes" Group="Minor" Delay="5"/>
         <ALTrTeTankTop Enable="No" Group="Minor" Delay="5"/>
         <ALTrTeTankBottom Enable="No" Group="Minor" Delay="5"/>
         <ALTrTeCTO Enable="No" Group="Other" Delay="5"/>
         <ALTrTeCBO Enable="No" Group="Other" Delay="5"/>

it continues on for 100 more lines with 100 different tags. I am trying to read in each ModelType child, tag and attribute, into an array of objects with out searching for each name using .find("name"). Any ideas on how to do this? I'm stumped and google has not been too helpful.

It may be possible without, but I like xpath, so you can do it like this:

import sys
import pprint
from lxml import etree

with open(sys.argv[1]) as xml_file:
    tree = etree.parse(xml_file)

pprint.pprint([(element.tag, element.attrib) for element in
       tree.xpath('//drCoreType/ModelType/*')])

This give:

[('ALTrVoltage', {'Enable': 'No', 'Group': 'Other', 'Delay': '0'}),
 ('ALTrCurrent', {'Enable': 'Yes', 'Group': 'Minor', 'Delay': '0'}),
 ('ALTrTeAmbient', {'Enable': 'Yes', 'Group': 'Minor', 'Delay': '5'}),
 ('ALTrTeTankTop', {'Enable': 'No', 'Group': 'Minor', 'Delay': '5'}),
 ('ALTrTeTankBottom', {'Enable': 'No', 'Group': 'Minor', 'Delay': '5'}),
 ('ALTrTeCTO', {'Enable': 'No', 'Group': 'Other', 'Delay': '5'}),
 ('ALTrTeCBO', {'Enable': 'No', 'Group': 'Other', 'Delay': '5'})]

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