Created 25 January 2004
Handyxml is a Python module that makes simple XML use convenient. It provides Python attributes for XML attributes and child elements, and provides a facade over two common XML parsers and an XPath implementation. It’s designed for casual XML use in environments such as template engines where data is stored in XML files.Download: handyxml.py
Imagine a simple XML file:
<!-- MyDataFile.xml -->
<property name='duck1' value='huey' />
<property name='duck2' value='louie' />
<property name='duck3' value='dewey' />
To parse the file, simply use the xml function:
>> import handyxml
>> doc = handyxml.xml('MyDataFile.xml')
It accepts either a filename or an open file as its argument, and parses the XML it finds. Its return value is the document element, and attributes on the element are available as attributes on the object:
The names of child elements are object attributes with lists of the child elements:
Unlike other Python XML-to-dictionary schemes, these objects act just like full-fledged DOM nodes, and so can be processed with other XML facilities.
Handyxml also provides the xpath function for evaluating XPath expressions. The first argument is either an argument acceptable to xml(), or a parsed XML node. The second argument is the XPath expression to evaluate against the XML. The return is the resulting list of XML nodes:
>> duck3 = handyxml.xpath(doc, '//property[@name="duck3"]')
When looking for a file, handyxml will search the list of directories specified in its path value, much like sys.path.
27 January 2004: The xml.xpath module is no longer required, and the xpath() function will raise an exception if the module couldn’t be imported. The xml() function can now take either a string (filename) or an open file as its argument.