Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

xml

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

like image 300
Anshul Avatar asked Jun 22 '11 12:06

Anshul


People also ask

How do I write data into an XML file using Python?

Creating XML Document using Python First, we import minidom for using xml. dom . Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks.

How do you process XML in Python?

To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree. parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot().


2 Answers

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))
like image 176
Antti Avatar answered Oct 03 '22 19:10

Antti


In python 3.x The proposed solution won't work unless you specify with open("filename", "wb") as f: instead of with open("filename", "w") as f:

like image 27
Emna Jaoua Avatar answered Oct 03 '22 19:10

Emna Jaoua