0

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.

1
  • What's the desired output? Also what have you tried so far? Commented Sep 14, 2017 at 20:14

1 Answer 1

1

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'})]
Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I was looking for. Thank you for your help!
@Akkarris you're welcome, don't hesitate to flag as answered if it's worth it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.