XML : Python3 parse XML into dictionary

I am very new to Python, and I'm trying to learn good Python practices for parsing XML files. Ultimately, I want to plot data extracted from several XML files, and I am thinking that a good way to do this will be to build up a list of dictionaries, where each dictionary has the timestamp and counter values from the XML files. Then when I go to plot, I'll use the timestamps and values to create the graphs.

Every XML file has a timestamp and the counters. For now, I am trying to extract the data from an XML file such as what follows:

  <?xml version="1.0"?>  <?xml-stylesheet type="text/xsl" href="Data.xsl" ?>  <!DOCTYPE mdc SYSTEM "Data.dtd">  <mdc xmlns:HTML="http://www.w3.org/TR/REC-xml">  <mfh>  <vn>TEST</vn>  <cbt>20140126234500.0+0000</cbt>  </mfh>  <mi>      <mts>20140126235000.0+0000</mts>      <mt>counter1</mt>      <mv>          <moid>DEFAULT</moid>          <r>58</r>      </mv>  </mi>  <mi>      <mts>20140126235000.0+0000</mts>      <mt>counter2</mt>      <mv>          <moid>DEFAULT</moid>          <r>100</r>      </mv>  </mi>  <mi>      <mts>20140126235000.0+0000</mts>      <mt>counter3</mt>      <mv>          <moid>DEFAULT</moid>          <r>7</r>      </mv>  </mi>  </mdc>    

From that I am hoping to build a dictionary like follows: {'cbt': 20140126234500.0+0000, 'counter1': 58, 'counter2': 100, 'counter3': 7}

I would like to use xml.etree.cElementTree since it seems to be standard and should be more than capable for my purposes. But I am having difficulty in building that dictionary from the XML file. I would greatly appreciate any pythonic solutions to this.

Thanks, Rusty

No comments:

Post a Comment