You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.

Answer from dgassaway on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ xml.etree.elementtree.html
xml.etree.ElementTree โ€” The ElementTree XML API
January 29, 2026 - Canonicalization is a way to normalise XML output in a way that allows byte-by-byte comparisons and digital signatures. It reduces the freedom that XML serializers have and instead generates a more constrained XML representation. The main restrictions regard the placement of namespace declarations, the ordering of attributes, and ignorable whitespace. 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.
Discussions

xml - Convert Python ElementTree to string - Stack Overflow
Whenever I call ElementTree.tostring(e), I get the following error message: AttributeError: 'Element' object has no attribute 'getroot' Is there any other way to convert an ElementTree object into... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python XML: how to treat a node content as a string? - Stack Overflow
Sign up to request clarification or add additional context in comments. ... from xml.etree import ElementTree import string tree=ElementTree.parse(file) rootElem=tree.getroot() More on stackoverflow.com
๐ŸŒ stackoverflow.com
parsing XML with Python and the RESTful API
To fetch the API response (the XML) you can use urllib2.urlopen() in the standard library . A popular third-party library which you may want to use instead is requests . Once you have the XML text you need to parse it. For most projects ElementTree is great - easy to program and in the standard library already . Here's a good example of processing XML with ElementTree: http://www.doughellmann.com/PyMOTW/xml/etree/ElementTree/parse.html Some projects are better suited to lxml, a third-party XML library that supports the same API as ElementTree but adds a bunch of more sophisticated features, such as a more complete XPath implementation. If you are parsing really big XML files (like several megabytes per document) then you would use a parser with a SAX API . This can save memory and speed processing but tends to make your program more complicated. More on reddit.com
๐ŸŒ r/learnpython
3
3
September 27, 2012
How to process / parse XML with Python
Best bet: Use lxml . There's a nice tutorial on the site, too . You can also use the built-in XML parser, either with ElementTree (common) or XML DOM (rarer) , or any other related library from the xml module , but most people prefer lxml, as it's much more powerful (and in parts, compatible with ElementTree). More on reddit.com
๐ŸŒ r/learnpython
5
11
October 22, 2017
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>
๐ŸŒ
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)) This opinionated guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis.
๐ŸŒ
lxml
lxml.de โ€บ tutorial.html
The lxml.etree Tutorial
The reasoning behind this difference is that parse() returns a complete document from a file, while the string parsing functions are commonly used to parse XML fragments.
๐ŸŒ
Apify
blog.apify.com โ€บ python-parse-xml
How to parse XML in Python
July 16, 2025 - Since weโ€™ve created an XML file with some book data, weโ€™ll use the parse() function to parse the XML data. However, weโ€™ll also show you how to use the fromstring() function to parse XML data stored in a string format.
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
Edureka
edureka.co โ€บ blog โ€บ python-xml-parser-tutorial
How to Parse and Modify XML in Python?
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.
Top answer
1 of 6
188

Element objects have no .getroot() method. Drop that call, and the .tostring() call works:

xmlstr = ElementTree.tostring(et, encoding='utf8')

You only need to use .getroot() if you have an ElementTree instance.

Other notes:

  • This produces a bytestring, which in Python 3 is the bytes type.
    If you must have a str object, you have two options:

    1. Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")

    2. Use encoding='unicode'; this avoids an encode / decode cycle:

      xmlstr = ElementTree.tostring(et, encoding='unicode')
      
  • If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8 as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?> declaration. Use utf-8 or UTF-8 (with a dash) if you want to prevent this. When using encoding="unicode" no declaration header is added.

2 of 6
81

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')

Example usage (Python 3)

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml, encoding='unicode')
print(xml_str)

Output:

<Person Name="John" />

Explanation

ElementTree.tostring() returns a bytestring by default in Python 2 & 3. This is an issue because Python 3 switched to using 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 you know what version of Python is being used, you should specify the encoding as unicode or utf-8. 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" />

Note: While xml_str = ElementTree.tostring().decode() is compatible with both Python 2 & 3, Christopher Rucinski pointed out that this method fails when dealing with non-Latin characters).

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 "canonical" way to convert an object to a string. However, using str() 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>
๐ŸŒ
lxml
lxml.de โ€บ parsing.html
Parsing XML and HTML with lxml
Otherwise, you can resort at runtime ... still provide a base URL for the document (e.g. to support relative paths in an XInclude), you can pass the base_url keyword argument: >>> root = etree.fromstring(xml, ......
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ xml.dom.minidom.html
xml.dom.minidom โ€” Minimal DOM implementation
The type DOMString maps to Python strings. xml.dom.minidom supports either bytes or strings, but will normally produce strings.
๐ŸŒ
Zyte
zyte.com โ€บ learn โ€บ a-practical-guide-to-xml-parsing-with-python
A Practical Guide to Python XML Parsing
Whether you're dealing with configuration files, SOAP-based APIs, or large datasets used in enterprise applications, understanding how to parse and manipulate XML is essential. In this guide, weโ€™ll dive into the world of XML parsing using ยท 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.
๐ŸŒ
Oxylabs
oxylabs.io โ€บ blog โ€บ python-parse-xml
How to Parse XML in Python
Notice the `&` symbol inside the message element, and this symbol is an invalid XML character; thus, all the standard XML libraries will fail to parse this XML file. Now letโ€™s try to parse this invalid XML using a couple of methods. For simple XML files like the above, you can preprocess the XML document as a string to remove the invalid elements or symbols from the XML document before passing it to the parser.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ xml-parsing-python
XML parsing in Python - GeeksforGeeks
June 28, 2022 - This article focuses on how one can parse a given XML file and extract some useful data out of it in a structured way. XML: XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable.That's why, the design goals of XML emphasize simplicity, generality, and usability across the Internet.
๐ŸŒ
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...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 43365805 โ€บ python-xml-how-to-treat-a-node-content-as-a-string โ€บ 43369208
Python XML: how to treat a node content as a string? - Stack Overflow
abcElem=root.find("abc") my_list = ["<{0.tag}>{0.text}</{0.tag}>".format(child) for child in abcElem] my_list.append(abcElem.text) my_val = string.join(my_list,"\n") I'm sure some other helpful soul knows a way to print these elements out using ElementTree or some other xml utility rather than formatting them yourself but this should start you off.
๐ŸŒ
Real Python
realpython.com โ€บ python-xml-parser
A Roadmap to XML Parsers in Python โ€“ Real Python
September 25, 2023 - It was an implementation several times faster than the same interface written in C. Today, the regular module uses the fast implementation whenever possible, so you donโ€™t need to bother anymore. You can use the ElementTree API by employing different parsing strategies: The non-incremental strategy loads up the entire document into memory in a DOM-like fashion. There are two appropriately named functions in the module that allow for parsing a file or a Python string with XML content:
๐ŸŒ
ScrapingDog
scrapingdog.com โ€บ blog โ€บ xml-parsing-python
How To Parse XML in Python (Detailed Guide)
May 7, 2025 - ElementTree is a class that wraps the element structure and allows the conversion to and from XML. It has the following properties: Each element that is present in the element module will consist of a tag that represents the type of data being stored. The attributes that are stored are Python dictionaries. A text string consisting of the information that needs to be displayed.
๐ŸŒ
Novixys Software
novixys.com โ€บ blog โ€บ parsing-xml-in-python
Parsing XML in Python | Novixys Software Dev Blog
January 4, 2017 - We use the ElementTree.fromstring() method to parse an XML string.