ElementTree : parse string input

R

rajarshi.guha

Hi, recently having discovered ElementTree I'm stumped by a very simple
problem, which I can't find the answer to.

I have some XML in a string object. Now the parse() method of
ElementTree takes a filename or file-like object. So I tried creating a
StringIO object from the original string and then giving that to
parse(). But that does not seem to work.

Any pointers to getting ElementTree to parse from a string would be
appreciated (of course I could dump it to a temp file, but that doesn't
seem elegent)

Thanks,
Rajarshi
 
F

Fredrik Lundh

Hi, recently having discovered ElementTree I'm stumped by a very simple
problem, which I can't find the answer to.

I have some XML in a string object. Now the parse() method of
ElementTree takes a filename or file-like object. So I tried creating a
StringIO object from the original string and then giving that to
parse(). But that does not seem to work.

that should work, but the fromstring function (and it's XML alias) is a
lot easier to use.

data = "some xml in a string"

elem = ElementTree.XML(data)

also see the end of this section:

http://www.effbot.org/zone/element.htm#reading-and-writing-xml-files

</F>
 
A

Amit Khemka

Any pointers to getting ElementTree to parse from a string would be
appreciated (of course I could dump it to a temp file, but that doesn't
seem elegent)

You can use the "fromstring" method.
Btw, did you looked at cElementTree module ? It claims to be much
'faster' and has very similar api as ElementTree Module.

link: http://effbot.org/zone/celementtree.htm

cheers,
amit.


--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top