XMLObject - Easy Python Object interface to XML data

XMLObject does for XML data what SQLObject does for databases - it frees you of the cumbersome API normally used for manipulating XML files, and gives you a simple and much more Pythonic object interface.

(This borrows some concepts from the xml_objectify.py, but adds the ability to save changes).


  • Create new XML files, or work with existing ones
  • Add, get and set tag attributes just like with Python
  • Iterate over given node objects, just like lists
  • Quickly find child tags by name, just like dicts
  • Save the modified XML file


Download your copy here


View the epydoc-generated manual


Based on an xml file containing:
<?xml version="1.0" encoding="UTF-8"?>
     <person name="John Smith" age="42">
        <!-- John Smith has an appeal in process against his last conviction -->
        <crime name="Armed robbery" date="March 11, 1994"/>
        <crime name="Aggravated burglary" date="June 9, 2001"/>
     <person name="Mary Jones" age="33">
        <crime name="Prostitution" date="January 8, 1997"/>
        <crime name="Selling heroin" date="September 4, 2002"/>
        <crime name="Manslaughter" date="December 21, 2004"/>
Here we go:
>>> from xmlobject import XMLFile
# open up an existing XML file
>>> x = XMLFile(path="sample.xml)

>>> print x
<xmlobject.XMLFile instance at 0xb7ccc52c>

# root node is in the .root attribute
>>> print x.root
<XMLNode: rapsheets>

# display contents of this node
>>> print x.root._children
[<XMLNode: text>, <XMLNode: person>, <XMLNode: text>,
 <XMLNode: person>, <XMLNode: text>]

# access only <person...> nodes
>>> print x.root.person
[<XMLNode: person>, <XMLNode: person>]

# Easily access the node's tag attributes
>>> print x.root.person[0].name
John Smith

# get a ref to the first <person> node
>>> john = x.root.person[0]

# Easy to change existing attributes, or set new ones
>>> john.height = 184

# Also easy to insert sub-nodes (and text nodes, and comments)
>>> c = john._addNode("crime")

# populate this <crime...> sub-node we've just added
>>> c.name = "Grand Theft Auto"
>>> c.date = "4 May, 2005"

# Render out to xml, compare this output with the above xml file
>>> print x.toxml()
<?xml version="1.0" ?>
 <person age="42" height="184" name="John Smith">
    <!-- John Smith has an appeal in process against his last conviction -->
    <crime date="March 11, 1994" name="Armed robbery"/>
    <crime date="June 9, 2001" name="Aggravated burglary"/>
    <crime date="4 May, 2005" name="Grand Theft Auto"/>
 <person age="33" name="Mary Jones">
    <crime date="January 8, 1997" name="Prostitution"/>
    <crime date="September 4, 2002" name="Selling heroin"/>
    <crime date="December 21, 2004" name="Manslaughter"/>

# Saving the changed xml tree back to a .xml file is a one-step operation
>>> x.save()