If you want to be able to parse the returned XML before doing stuff with it, the xml tree is your friend.

import requests
import xml.etree.ElementTree as ET

r = requests.get('url',  auth=('user', 'pass'))
tree = ET.parse(r.text)
root = tree.getroot()

Otherwise, as jordanm has commented, you could just save it to a file and be done with it.

with open('data.xml', 'w') as f:
    f.write(r.text)
Answer from enigma on Stack Overflow
🌐
Pybites
pybit.es › articles › download-xml-file
How to Download an XML File with Python – Pybites
May 4, 2017 - The nicer and Pythonic thing to do is to have a separate script that does the request once and saves the required data to a local file. Your primary scraping or analysis script then references the local file.
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python - GeeksforGeeks
August 10, 2024 - Beautiful Soup supports the HTML parser included in Python’s standard library, but it also supports a number of third-party Python parsers. One is the lxml parser (used for parsing XML/HTML documents). lxml could be installed by running the following command in the command processor of your Operating system: ... Firstly we will learn how to read from an XML file. We would also parse data stored in it. Later we would learn how to create an XML file and write data to it.
🌐
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...
🌐
Stack Abuse
stackabuse.com › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python
November 30, 2017 - As we can see when comparing with the original XML file, the names of the item elements have changed to "newitem", the text to "new text", and the attribute "name2" has been added to both nodes. You may also notice that writing XML data in this way (calling tree.write with a file name) adds some more formatting to the XML tree so it contains newlines and indentation.
🌐
Guru99
guru99.com › home › python › python xml file – how to read, write & parse
Python XML File – How to Read, Write & Parse
August 12, 2024 - Run the code- It prints out the nodename (#document) from the XML file and the first child tagname (employee) from the XML file ... Nodename and child tagname are the standard names or properties of an XML dom. Step 3) Call the list of XML tags from the XML document and printed out · Next, We can also call the list of XML tags from the XML document and printed out. Here we printed out the set of skills like SQL, Python, Testing and Business.
Find elsewhere
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'))
🌐
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 - By using either of these methods, you can read XML files efficiently. To write XML in Python, you can use the ElementTree XML API library.
🌐
Python Module of the Week
pymotw.com › 2 › xml › etree › ElementTree › create.html
Creating XML Documents - Python Module of the Week
When working with large amounts of data, it will take less memory and make more efficient use of the I/O libraries to write directly to a file handle using the write() method of ElementTree. import sys from xml.etree.ElementTree import Element, SubElement, Comment, ElementTree top = Element('top') ...
🌐
Quora
quora.com › Can-I-save-my-Python-variables-to-an-XML-file
Can I save my Python variables to an XML file? - Quora
Answer (1 of 4): You can save the contents of any variables to a file in any data format you can think of, including XML, JSON, CSV, etc… You’ll need to think about how you structure your data and how you serialise it, for this to work effectively. The built-in Python [code ]xml[/code] ...
🌐
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 › xml-parsing-python
XML parsing in Python - GeeksforGeeks
June 28, 2022 - Our goal is to process this RSS feed (or XML file) and save it in some other format for future use. Python Module used: This article will focus on using inbuilt xml module in python for parsing XML and the main focus will be on the ElementTree XML API of this module.
🌐
Zyte
zyte.com › learn › a-practical-guide-to-xml-parsing-with-python
A Practical Guide to Python XML Parsing
Python, providing not just basic methods but also advanced techniques like handling XML namespaces, performing XPath queries, and mapping XML data to custom Python objects. By the end, you will have a deep understanding of how to read, modify, and write XML files efficiently using Python.
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-xml-documents-using-python
Create XML Documents using Python - GeeksforGeeks
July 12, 2025 - from xml.dom import minidom import os root = minidom.Document() xml = root.createElement('root') root.appendChild(xml) productChild = root.createElement('product') productChild.setAttribute('name', 'Geeks for Geeks') xml.appendChild(productChild) xml_str = root.toprettyxml(indent ="\t") save_path_file = "gfg.xml" with open(save_path_file, "w") as f: f.write(xml_str) Output: 2) Creating XML document using ElementTree Firstly we have to import 'xml.etree.ElementTree' for creating a subtree. After that, we make root element, and that root element should be in an intended block otherwise the error will arise. After creating the root element, we can create a tree structure easily. Then the file will be stored as 'name you want to give to that file.xml'. ElementTree is an important Python library that allows you to parse and navigate an XML document.
🌐
Python.org
discuss.python.org › python help
Logging to XML file - Python Help - Discussions on Python.org
February 25, 2023 - “Hacky version”: open the file; delete last line; append new entries; add closing tag; close file (similar to rob42’s answer) “Proper version”: use xml.etree.ElementTree.write()