Alex Rivera | Logout

How do i parse a string in python and write it as an xml to a new xml file?

Asked 2011-06-22T12:48:52.957
16

I have xml data in string format which is in variable xml_data

xml_data="<?xml version="1.0"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>"

I want to save this data to a new xml file through python.

I am using this code:

from xml.etree import ElementTree as ET
tree = ET.XML(xml_data)

Now Here i want to create a xml file and save the xml tree to the file, but don't know which function to use for this.

Thanks

Edit
Report

1 Answer

17

With ET.tostring(tree) you get a non-formatted string representation of the XML. To save it to a file:

with open("filename", "w") as f:
    f.write(ET.tostring(tree))
answered 2011-06-22T12:58:45.657

Your Answer