tags:

views:

43

answers:

2

i have made a xml file using python. how can i retrieve an element from it? will u help me with the code?

Also i need to have my output(i.e. element of each attribute come in seperate lines in that particular xml file)

A: 

Python comes with 2 modules for xml processing mindom which is a DOM implemetation and the more 'pythonic' Element Tree which has other information and links to examples etc I use a third party library lxml which is in effect a super set of Element Tree

Mark
A: 

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
Peter Hoffmann