I have also been looking for a simple way to transform data between XML documents and Python data structures, something similar to Golang's XML library which allows you to declaratively specify how to map from data structures to XML.
I was unable to find such a library for Python, so I wrote one to meet my need called declxml for declarative XML processing.
With declxml, you create processors which declaratively define the structure of your XML document. Processors are used to perform both parsing and serialization as well as a basic level of validation.
Parsing this XML data into a list of dictionaries with declxml is straightforward
import declxml as xml
xml_string = """
<encspot>
<file>
<Name>some filename.mp3</Name>
<Encoder>Gogo (after 3.0)</Encoder>
<Bitrate>131</Bitrate>
</file>
<file>
<Name>another filename.mp3</Name>
<Encoder>iTunes</Encoder>
<Bitrate>128</Bitrate>
</file>
</encspot>
"""
processor = xml.dictionary('encspot', [
xml.array(xml.dictionary('file', [
xml.string('Name'),
xml.string('Encoder'),
xml.integer('Bitrate')
]), alias='files')
])
xml.parse_from_string(processor, xml_string)
Which produces the following result
{'files': [
{'Bitrate': 131, 'Encoder': 'Gogo (after 3.0)', 'Name': 'some filename.mp3'},
{'Bitrate': 128, 'Encoder': 'iTunes', 'Name': 'another filename.mp3'}
]}
Want to parse the data into objects instead of dictionaries? You can do that as well
import declxml as xml
class AudioFile:
def __init__(self):
self.name = None
self.encoder = None
self.bit_rate = None
def __repr__(self):
return 'AudioFile(name={}, encoder={}, bit_rate={})'.format(
self.name, self.encoder, self.bit_rate)
processor = xml.array(xml.user_object('file', AudioFile, [
xml.string('Name', alias='name'),
xml.string('Encoder', alias='encoder'),
xml.integer('Bitrate', alias='bit_rate')
]), nested='encspot')
xml.parse_from_string(processor, xml_string)
Which produces the output
[AudioFile(name=some filename.mp3, encoder=Gogo (after 3.0), bit_rate=131),
AudioFile(name=another filename.mp3, encoder=iTunes, bit_rate=128)]