This should work:-

xmlstr = ET.tostring(root, encoding='utf8', method='xml')
Answer from Stephen Briney on Stack Overflow
Top answer
1 of 2
22

This should work:-

xmlstr = ET.tostring(root, encoding='utf8', method='xml')
2 of 2
10

How do I convert ElementTree.Element to a String?

For Python 3:

xml_str = ElementTree.tostring(xml, encoding='unicode')

For Python 2:

xml_str = ElementTree.tostring(xml, encoding='utf-8')

For compatibility with both Python 2 & 3:

xml_str = ElementTree.tostring(xml).decode()

Example usage

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml).decode()
print(xml_str)

Output:

<Person Name="John" />

Explanation

Despite what the name implies, ElementTree.tostring() returns a bytestring by default in Python 2 & 3. This is an issue in Python 3, which uses Unicode for strings.

In Python 2 you could use the str type for both text and binary data. Unfortunately this confluence of two different concepts could lead to brittle code which sometimes worked for either kind of data, sometimes not. [...]

To make the distinction between text and binary data clearer and more pronounced, [Python 3] made text and binary data distinct types that cannot blindly be mixed together.

Source: Porting Python 2 Code to Python 3

If we know what version of Python is being used, we can specify the encoding as unicode or utf-8. Otherwise, if we need compatibility with both Python 2 & 3, we can use decode() to convert into the correct type.

For reference, I've included a comparison of .tostring() results between Python 2 and Python 3.

ElementTree.tostring(xml)
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml, encoding='unicode')
# Python 3: <Person Name="John" />
# Python 2: LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3: <Person Name="John" />
# Python 2: <Person Name="John" />

Thanks to Martijn Peters for pointing out that the str datatype changed between Python 2 and 3.


Why not use str()?

In most scenarios, using str() would be the "cannonical" way to convert an object to a string. Unfortunately, using this with Element returns the object's location in memory as a hexstring, rather than a string representation of the object's data.

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
print(str(xml))  # <Element 'Person' at 0x00497A80>
🌐
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.
Discussions

extracting a string from an XML file
When trying to read content from XML or other structured content what you want to do is use a parser. Python comes with an XML parsing library which will read the file and give you structure to pull the data from, rather than searching for strings. Start there! More on reddit.com
🌐 r/learnpython
7
2
May 4, 2014
A Roadmap to XML Parsers in Python – Real Python
Heh, this would have been so useful for me a week ago, when I needed to parse an XML. Found xmltodict and it served its purpose beautifully - for what I needed at least. More on reddit.com
🌐 r/Python
14
88
October 19, 2021
Can someone explain to me how to parse an XML file?
The standard library has XML libraries, you could search in the docs on Python.org for those. The lxml library is also popular for this. Sorry I can't help with details, I haven't had to work with XML in a few years. More on reddit.com
🌐 r/learnpython
8
1
June 25, 2022
🌐
LearnPython.com
learnpython.com › blog › read-xml-into-python
How to Read XML Files into Python | LearnPython.com
Finally, we print the extracted information for each book in a formatted string. This displays the title, author, and price of each book. We can also use BeautifulSoup to read an XML file into Python. BeautifulSoup is a third-party Python library used to parse data stored as markup language.
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python - GeeksforGeeks
January 12, 2026 - It is both human-readable and machine-readable. Let’s look at two libraries used for XML parsing in Python. BeautifulSoup is mainly used for HTML parsing, but when combined with the lxml parser, it can also parse XML files efficiently. ... from bs4 import BeautifulSoup with open('dict.xml', 'r') as f: data = f.read() Bs_data = BeautifulSoup(data, "xml") b_unique = Bs_data.find_all('unique') print(b_unique) b_name = Bs_data.find('child', {'name':'Frank'}) print(b_name) value = b_name.get('test') print(value)
🌐
ScrapingDog
scrapingdog.com › blog › xml-parsing-python
How To Parse XML in Python (Detailed Guide)
May 7, 2025 - The attributes that are stored are Python dictionaries. A text string consisting of the information that needs to be displayed. An optional tail string. Child elements that consist of other specific data. Now, we will learn how this module can be used for parsing an XML document. There are two ways to parse the XML file with this module: ... Consider this sample XML data. I am naming this file as ...
🌐
Runestone Academy
runestone.academy › ns › books › published › py4e-int › web › parsingXML.html
15.2. Parsing XML — Python for Everybody - Interactive
Here is a simple application that parses some XML and extracts some data elements from the XML: Run this to see what it prints. The triple single quote ('''), as well as the triple double quote ("""), allow for the creation of strings in Python that span multiple lines.
🌐
lxml
lxml.de › parsing.html
Parsing XML and HTML with lxml
The result of tostring(encoding='unicode') can be treated like any other Python unicode string and then passed back into the parsers. However, if you want to save the result to a file or pass it over the network, you should use write() or tostring() with a byte encoding (typically UTF-8) to ...
Find elsewhere
🌐
The Hitchhiker's Guide to Python
docs.python-guide.org › scenarios › xml
XML parsing — The Hitchhiker's Guide to Python
from xmlschema import XMLSchema, etree_tostring # load a XSD schema file schema = XMLSchema("your_schema.xsd") # validate against the schema schema.validate("your_file.xml") # or schema.is_valid("your_file.xml") # decode a file data = schmema.decode("your_file.xml") # encode to string s = etree_tostring(schema.encode(data))
🌐
GitHub
github.com › oxylabs › how-to-parse-xml-in-python
GitHub - oxylabs/how-to-parse-xml-in-python: Follow this in-depth technical tutorial to learn how to parse XML data in Python, what libraries you should use, how to handle invalid XML, and more. · GitHub
You can use the untangle library to convert XML documents directly to a Python dictionary object. The code is self-explanatory. import untangle parsed_dict = untangle.parse("sample.xml") The cool thing about this library is, you can pass a URL, ...
Author   oxylabs
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.read_xml.html
pandas.read_xml — pandas documentation - PyData |
>>> df = pd.read_xml(StringIO(xml)) >>> df shape degrees sides 0 square 360 4.0 1 circle 360 NaN 2 triangle 180 3.0
🌐
Edureka
edureka.co › blog › python-xml-parser-tutorial
Python XML Parser Tutorial | ElementTree and Minidom Parsing | Edureka
December 5, 2024 - The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.
🌐
Oxylabs
oxylabs.io › blog › python-parse-xml
How to Parse XML in Python
So far, you’ve learned how to parse XML files from Python string objects. Now, let’s learn how to parse XML files using these libraries. Fortunately, both `minidom` and `ElementTree` provide a built-in function to parse XML files. You can use the `parse` method of `minidom` to read XML content ...
🌐
PythonForBeginners.com
pythonforbeginners.com › home › working with an xml file in python
Working With an XML File in Python - PythonForBeginners.com
February 27, 2023 - Once we get the file pointer, we will read the file using the read() method. The read() method, when invoked on the file pointer, returns the file contents as a python string. Now, we have read the XML file into a string.
🌐
Real Python
realpython.com › python-xml-parser
A Roadmap to XML Parsers in Python – Real Python
September 25, 2023 - If you’re looking for a one-liner that could turn your XML document into a Python object, then look no further. While it hasn’t been updated in a few years, the untangle library might soon become your favorite way of parsing XML in Python. There’s only one function to remember, and it accepts a URL, a filename, a file object, or an XML string:
🌐
Zyte
zyte.com › learn › a-practical-guide-to-xml-parsing-with-python
A Practical Guide to Python XML Parsing
ET.parse() loads the XML file into an element tree. getroot() retrieves the root element of the XML structure, which is the starting point for further exploration. Sometimes, XML data is delivered as a string—especially when working with web services or APIs.
🌐
DataCamp
datacamp.com › tutorial › python-xml-elementtree
Python XML Tutorial: Element Tree Parse & Read | DataCamp
December 10, 2024 - Check for common issues like malformed ... file paths. Use Python's error handling mechanisms (try-except blocks) to diagnose and manage parsing errors gracefully. ElementTree does not support pretty-printing directly, but you can use xml.dom.minidom to parse the XML string and then use its toprettyxml() method to format the XML for readability...
🌐
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.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-parse-xml-in-python-without-using-external-libraries
How to Parse XML in Python Without Using External Libraries
November 12, 2025 - We convert numeric strings to proper types (float for price, int for stock) For nested categories, we first check if the <categories> element exists. Then we iterate through child <category> elements and collect their text · The result is clean Python data structures you can easily work with. You can now use the parser like so: products = parse_product_catalog('products.xml') for product in products: print(f"\nProduct: {product['name']}") print(f" ID: {product['id']}") print(f" Price: {product['currency']} {product['price']}") print(f" Stock: {product['stock']}") print(f" Categories: {', '.join(product['categories'])}")
🌐
Guru99
guru99.com › home › python › python xml file – how to read, write & parse
Python XML File – How to Read, Write & Parse
August 12, 2024 - Learn how to create,read, and parse XML Files in Python using minidom class and ElementTree. Python XML Tutorial with Example.
🌐
Studytonight
studytonight.com › python-howtos › how-to-read-xml-file-in-python
How to read XML file in Python - Studytonight
In this article, we will learn how to use different parsing modules to read XML documents in Python and some related custom examples as well.