NoviceInPython
NoviceInPython

Reputation: 123

Converting XML element into string and again string to XML file in python

How would I convert an XML element into string and a string back to XML format using xml.elementtree in web2py ?

Upvotes: 3

Views: 8514

Answers (2)

Devi
Devi

Reputation: 5453

Use parseString to get xml element from string and toxml to make string out of xml element. Something like this.

from xml.dom.minidom import parseString

dom = minidom.parseString(content)
...
# do some changes to dom here
return dom.toxml()

Upvotes: 2

Eli Courtwright
Eli Courtwright

Reputation: 193241

Using the standard library, you'd use the StringIO writer and the parseString function:

>>> from StringIO import StringIO
>>> from xml.dom.minidom import parseString
>>> e = parseString('<foo/>')
>>> out = StringIO()
>>> e.writexml(out)
>>> s = out.getvalue()
>>> print(s)
<?xml version="1.0" ?><foo/>
>>> e2 = parseString(s)

Upvotes: 1

Related Questions