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))
Answer from Antti on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python - GeeksforGeeks
January 12, 2026 - import xml.etree.ElementTree as ET root = ET.Element('chess') opn = ET.SubElement(root, 'Opening') e4 = ET.SubElement(opn, 'E4') d4 = ET.SubElement(opn, 'D4') e4.set('type', 'Accepted') d4.set('type', 'Declined') e4.text = "King's Gambit Accepted" d4.text = "Queen's Gambit Declined" xml_data = ET.tostring(root) with open("GFG.xml", "wb") as f: f.write(xml_data) ... ET.Element('chess'): Creates the root XML element <chess>. ET.SubElement(root, 'Opening'): Adds a child element <Opening> under <chess>. ET.SubElement(opn, 'E4') and ET.SubElement(opn, 'D4'): Create sub-elements <E4> and <D4>. .set('type', ...): Adds attributes to the elements. ... ET.tostring(root): Converts the XML tree into bytes. Writing to "GFG.xml": Saves the generated XML to a file.
Discussions

Creating a simple XML file using python - Stack Overflow
What are my options if I want to create a simple XML file in python? (library wise) The xml I want looks like: some value1 ... More on stackoverflow.com
🌐 stackoverflow.com
Python writing to an xml file - Stack Overflow
I am trying to write to an xml file. I have changed a specific element in my code, and am able to get it to print successfully. I need to have it written to the file, without changing the structu... More on stackoverflow.com
🌐 stackoverflow.com
August 27, 2016
How to save an XML file to disk with python? - Stack Overflow
Please show us how you attempted to use writexml() and how it failed to work (was there an error message? or did it fail to work as you intended?) 2012-03-30T01:19:37.167Z+00:00 ... Read about python files, if you xml as string you can just write it to a file e.g. More on stackoverflow.com
🌐 stackoverflow.com
How to create XML file using Python? - Stack Overflow
Add encoding information to the xml declaration part by simply splitting and concating the formatted string More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
January 29, 2026 - This function takes an XML data string (xml_data) or a file path or file-like object (from_file) as input, converts it to the canonical form, and writes it out using the out file(-like) object, if provided, or returns it as a text string if not. The output file receives text, not bytes.
Top answer
1 of 6
424

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5. Deprecated and folded into the regular ElementTree as an automatic thing as of 3.3.)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

  • API docs for the implementation in the Python standard library
  • Introductory Tutorial (From the original author's site)
  • LXML etree tutorial. (With example code for loading the best available option from all major ElementTree implementations)

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.
2 of 6
79

The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:

#!/usr/bin/python
import lxml.etree
import lxml.builder    

E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2

the_doc = ROOT(
        DOC(
            FIELD1('some value1', name='blah'),
            FIELD2('some value2', name='asdfasd'),
            )   
        )   

print lxml.etree.tostring(the_doc, pretty_print=True)

Output:

<root>
  <doc>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>
  </doc>
</root>

It also supports adding to an already-made node, e.g. after the above you could say

the_doc.append(FIELD2('another value again', name='hithere'))
🌐
Python Module of the Week
pymotw.com › 2 › xml › etree › ElementTree › create.html
Creating XML Documents - Python Module of the Week
$ python ElementTree_extend_no... <child id="4300110480" num="2"/> </parent> </top> tostring() is implemented to write to an in-memory file-like object and then return a string representing the entire element tree....
🌐
Stack Abuse
stackabuse.com › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python
November 30, 2017 - 3. Although we can add our attributes with the SubElement function, we can also use the set() function, as we do in the following code. The element text is created with the text property of the Element object. 4. In the last 3 lines of the code below we create a string out of the XML tree, and we write that data to a file we open.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › create-xml-documents-using-python
Create XML Documents using Python
The above code creates an XML file called 'person.xml' and writes the XML contents to the file.
🌐
Board Infinity
boardinfinity.com › blog › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python | Board Infinity
August 13, 2025 - Now at last we will convert the data type of the content to bytes objects from the ‘XML.etree.ElementTree.Element’ with the help of a function named as toString(). Lastly, we will flush all the data to a file named gos.xml which will be opened in writing binary mode.
🌐
GeeksforGeeks
geeksforgeeks.org › create-xml-documents-using-python
Create XML Documents using Python - GeeksforGeeks
May 10, 2020 - Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks. After creating a child product the filename is saved as 'any name as per your choice.xml'. Do not forget to append .xml at the end of the filename you have given to the file.
🌐
Python Forum
python-forum.io › thread-35417.html
how I write the output into xml file in python?
I have an automatically generated j son, I load it in the file (it is a list of dictionaries) and then I convert it to xml but how do I move the output to an 'xml1.xml' file? import json from dicttoxml import dicttoxml with open('json_gen...
🌐
STechies
stechies.com › reading-writing-xml-files-python
Reading and Writing XML Files in Python
September 16, 2021 - Now to fit the text inside the ... with the assignment operator. Append the child item object with the root object and write the XML file using the write() method and pass a filename as string....
🌐
Dive into Python
diveintopython.org › home › learn python programming › file handling and file operations › xml files handling
XML File Operations with Python - Read, Write and Parse XML Data
May 3, 2024 - In both of these examples, the xml.etree.ElementTree module is used to parse the XML file and extract the data. The csv module (in Example 1) or the pandas library (in Example 2) is used to write the data to a CSV file. Do not hesitate to contribute to Python tutorials on GitHub: create a fork, update content and issue a pull request.
🌐
Guru99
guru99.com › home › python › python xml file – how to read, write & parse
Python XML File – How to Read, Write & Parse
August 12, 2024 - To add a new XML and add it to the document, we use code “doc.create elements” · This code will create a new skill tag for our new attribute “Big-data” · Add this skill tag into the document first child (employee) Run the code- the new tag “big data” will appear with the other list of expertise · How to Create (Write) Text File in Python · type() and isinstance() in Python with Examples · Python String split(): List, By Character, Delimiter EXAMPLE ·
🌐
PythonForBeginners.com
pythonforbeginners.com › home › convert python dictionary to xml string or file
Convert Python Dictionary to XML String or File - PythonForBeginners.com
February 15, 2023 - The open() function takes the file ... pointer. Once we get the file pointer, we will write the XML string into the file using the write() method....
Top answer
1 of 2
18

You probably want to use Node.writexml() on the root node of your XML DOM tree. This will write your root element and all child elements to an XML file, doing all the becessary indenting etc. along the way.

See the documentation for xml.dom.minidom:

Node.writexml(writer[, indent=""[, addindent=""[, newl=""]]])

Write XML to the writer object. The writer should have a write() method which matches that of the file object interface. The indent parameter is the indentation of the current node. The addindent parameter is the incremental indentation to use for subnodes of the current one. The newl parameter specifies the string to use to terminate newlines.

For the Document node, an additional keyword argument encoding can be used to specify the encoding field of the XML header.

Changed in version 2.1: The optional keyword parameters indent, addindent, and newl were added to support pretty output.

Changed in version 2.3: For the Document node, an additional keyword argument encoding can be used to specify the encoding field of the XML header.

Usage will be somewhat like:

file_handle = open("filename.xml","wb")
Your_Root_Node.writexml(file_handle)
file_handle.close()
2 of 2
7

Read about python files, if you xml as string you can just write it to a file e.g.

xml = "<myxmldata/>"
f =  open("myxmlfile.xml", "wb")
f.write(xml)
f.close()

To obtain xml string from minidom nodes you can either use

xml = Node.toxml()

or you can directly write to a object which supports write e.g. a file

Node.writexml(f)
🌐
Edureka Community
edureka.co › home › community › categories › python › writing output to new file using xml etree...
Writing output to new file using xml etree ElementTree in python | Edureka Community
July 24, 2019 - I want to write my xml output to a new file instead of making changes to the original file. ... I do? I have been using xml.etree.ElementTree module
🌐
PythonForBeginners.com
pythonforbeginners.com › home › working with an xml file in python
Working With an XML File in Python - PythonForBeginners.com
February 27, 2023 - Next, we will write the XML string into the file using the write() method. The write() method, when invoked on the file pointer, takes the XML string as its input argument and writes it to the file.
🌐
MicroPyramid
micropyramid.com › blog › building-and-parsing-xml-document-using-python
Building and Parsing XML Document using Python | MicroPyramid
In addition to parsing XML, xml.etree.ElementTree used for creating well-formed documents from Element objects in an application. The Element class used when a document is parsed also knows how to generate a serialized form of its contents, which can then be written to a file.