-1

I have made a XML file using python. How can I retrieve an element from it? Will you help me with the code?

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

1
  • Please provide a sample of the XML you've got and what data you want to extract from it
    – MattH
    Feb 23, 2010 at 11:40

2 Answers 2

0

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.