github.com/hoffmann Peter Hoffmann on Stackoverflow @peterhoffmann on twitter Peter Hoffmann on Facebook Contact me per email Subscribe to Atom Feed

Peter Hoffmann

Software Engineer
prev page next page

xml file using python

Posted on February 23, 2010
#stackoverflow #python

This my Answer to the stackoverflow question: xml file using python:

There is also the excellent lxml library. You can query the tree with xpath or if you are familiar with css you can select elements with cssselect.

In [1]: from lxml import etree
In [2]: from StringIO import StringIO
In [3]: f = StringIO('<foo><bar id="1">hello</bar><bar id="2">world</bar></foo>')
In [4]: tree = etree.parse(f)
In [5]: r = tree.xpath('/foo/bar')
In [6]: print len(r)
2
In [7]: for elem in r:
   ....:     print elem.get('id'), elem.text   
1 hello
2 world