ClassyXml
An xml file parser that makes the element text and attributes of an xml file accessible as ClassyXml class attributes.
Install it from PyPI
pip install classyxml
Usage
Parsing an XML file
<root>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
</root>
from classy_xml import ClassyXml
classy = ClassyXml('countries.xml')
print(len(classy.country))
print(classy.country[0].name)
print(classy.country[0].rank.text)
print(classy.country[0].year.text)
print(classy.country[0].gdppc.text)
print(len(classy.country[0].neighbor))
print(classy.country[0].neighbor[0].name)
print(classy.country[0].neighbor[0].direction)
print(classy.country[0].neighbor[1].name)
print(classy.country[0].neighbor[1].direction)
print(classy.country[1].name)
print(classy.country[1].rank.text)
print(classy.country[1].year.text)
print(classy.country[1].gdppc.text)
print(len(classy.country[1].neighbor))
print(classy.country[1].neighbor.name)
print(classy.country[1].neighbor.direction)
Generating an XML file
This will generate the countries.xml file illustrated above.
from classy_xml import ClassyXml, XmlElement
classy = ClassyXml()
liechtenstein = XmlElement(attributes={'name': 'Liechtenstein'})
liechtenstein.rank = XmlElement(text=1)
liechtenstein.year = XmlElement(text=2008)
liechtenstein.gdppc = XmlElement(text=141100)
liechtenstein.neighbor = XmlElement(attributes={'name': 'Austria', 'direction': 'E'})
liechtenstein.neighbor = XmlElement(attributes={'name': 'Switzerland', 'direction': 'W'})
singapore = XmlElement()
singapore.name = 'Singapore'
singapore.rank = XmlElement()
singapore.rank.text = 4
singapore.year = XmlElement()
singapore.year.text = 2011
singapore.gdppc = XmlElement()
singapore.gdppc.text = 59900
singapore.neighbor = XmlElement()
singapore.neighbor[0].name = 'Malaysia'
singapore.neighbor[0].direction = 'N'
classy.country = liechtenstein
classy.country = singapore
classy.save_as('countries.xml')
Modifying an existing XML file
This will add a USA element to the countries.xml file illustrated above.
from classy_xml import ClassyXml, XmlElement
classy = ClassyXml('countries.xml')
usa = XmlElement(attributes={'name': 'USA'})
usa.rank = XmlElement(text=2)
usa.year = XmlElement(text=2012)
usa.gdppc = XmlElement(text=12345)
usa.neighbor = XmlElement(attributes={'name': 'Canada', 'direction': 'N'})
usa.neighbor = XmlElement(attributes={'name': 'Mexico', 'direction': 'S'})
classy.country = usa
classy.save()