Personal tools
You are here: Home Python simplexml

simplexml

Module for simple access to simple xml


Example of usage of simplexml module

To run this doctest (if stored in file named 'simplexml.txt') from command/shell prompt:

python -c"import doctest; doctest.testfile('simplexml.txt')" -v


Create simplexml object from xml text (or file):
>>> from simplexml import simplexml
>>> xml = """
... <root>
... <item name="item1" caption="Item1" />
... <item name="item2" caption="Item2" />
... <link name="link1" caption="Link1" />
... <link name="link2" caption="Link2" />
... </root>
... """
>>> s = simplexml(xml)


Get list of child elements of tag name = 'item':
>>> s.item #doctest: +ELLIPSIS
[<DOM Element: item at ...>, <DOM Element: item at ...>]


Get value of the first item element's attribute 'name':
>>> s.item[0]['name']
u'item1'


Find the child item element with given value of attribute 'name' and get
value of it's attribute 'caption':
attribute
>>> s.item("name == 'item1'")['caption']
u'Item1'


For attributes 'name' or 'id' the search expression can be abbreviated
just to the value of that attribute:
>>> s.item('item2')['caption']
u'Item2'


Get list of attributes of the element:
>>> item = s.item[0]
>>> item.attrNames
[u'caption', u'name']


Get item tag name:
>>> item.tagName
'item'


Get list of all child element tag names:
>>> s.tagNames
['item', 'link']




Document Actions