This has nothing to do with the xml file format, but in which encoding your file is. Python3 assumes everything to be in utf-8, but if you are on windows your file is probably in windows-1252. You should use:

f = open("text.txt", "r", encoding="cp1252")
Answer from syntonym 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 - 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.
Discussions

Converting a Python XML ElementTree to a String - Stack Overflow
Thanks to Martijn Peters for pointing ... between Python 2 and 3. 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 ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python parse xml text - Stack Overflow
I would like to parse xml in python, but as a string, not taken from a file. Can someone help me do this? More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 10, 2011
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
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
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ xml.etree.elementtree.html
xml.etree.ElementTree โ€” The ElementTree XML API
January 29, 2026 - Source code: Lib/xml/etree/ElementTree.py The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Tutorial: This is a short tutorial for using xml....
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>
๐ŸŒ
LearnPython.com
learnpython.com โ€บ blog โ€บ read-xml-into-python
How to Read XML Files into Python | LearnPython.com
But for now, let's find out how to work with XML in Python! XML (short for Extensible Markup Language) is a plain text file format designed to store and transport data. Its main feature is that data is stored in an arbitrary hierarchy. This is a direct contrast to other plain text formats that store data, such as a CSV table (which you can read ...
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.read_xml.html
pandas.read_xml โ€” pandas documentation - PyData |
String path, path object (implementing os.PathLike[str]), or file-like object implementing a read() function. The string can be a path. The string can further be a URL. Valid URL schemes include http, ftp, s3, and file. ... The XPath to parse required set of nodes for migration to DataFrame.``XPath`` should return a collection of elements and not a single element. Note: The etree parser supports limited XPath expressions. For more complex XPath, use lxml which requires installation. ... The namespaces defined in XML document as dicts with key being namespace prefix and value the URI.
๐ŸŒ
lxml
lxml.de โ€บ parsing.html
Parsing XML and HTML with lxml
As known from ElementTree, the iterparse() utility function returns an iterator that generates parser events for an XML file (or file-like object), while building the tree. You can think of it as a blocking wrapper around the XMLPullParser that automatically and incrementally reads data from the input file for you and provides a single iterator for them: >>> xml = ''' ... <root> ... <element key='value'>text</element> ...
Find elsewhere
๐ŸŒ
ScrapingDog
scrapingdog.com โ€บ blog โ€บ xml-parsing-python
How To Parse XML in Python (Detailed Guide)
May 7, 2025 - We are loading the file sample.xml ... element of the XML, which is <note> in this case. Finally, we search for the <to> tag inside the root and get its text content....
๐ŸŒ
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.
๐ŸŒ
Oxylabs
oxylabs.io โ€บ blog โ€บ python-parse-xml
How to Parse XML in Python
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 from a file.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-xml-elementtree
Python XML Tutorial: Element Tree Parse & Read | DataCamp
December 10, 2024 - Parse and read XML data with Element Tree Python package. Learn how to use xml.etree.elementtree and explore your data through XML today!
๐ŸŒ
Edureka
edureka.co โ€บ blog โ€บ python-xml-parser-tutorial
Python XML Parser Tutorial | ElementTree and Minidom Parsing | Edureka
December 5, 2024 - In this Python XML Parser Tutorial, you will learn how to parse, read, modify and find elements from XML files in Python using ElementTree and Minidom.
๐ŸŒ
ScrapingAnt
scrapingant.com โ€บ blog โ€บ python-parse-xml
How to Parse XML in Python | ScrapingAnt
August 2, 2024 - For secure XML parsing, consider using the defusedxml library (defusedxml documentation), which provides safe replacements for all of Python's standard library XML parsers: from defusedxml import ElementTree as ET # Parse the XML file safely tree = ET.parse('example.xml') # Get the root element root = tree.getroot()
๐ŸŒ
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 - Always check if find() returns None before accessing .text or .get() Use .get('attr', 'default') to provide default values for missing attributes ยท Consider wrapping parsing in try-except blocks for production code ยท Validate your data after parsing rather than assuming XML structure is correct ยท You now know how to parse XML in Python without installing any external libraries. You learned: How to read XML from strings and files ยท
๐ŸŒ
The Hitchhiker's Guide to Python
docs.python-guide.org โ€บ scenarios โ€บ xml
XML parsing โ€” The Hitchhiker's Guide to Python
import xmltodict with open('path/to/file.xml') as fd: doc = xmltodict.parse(fd.read()) and then you can access elements, attributes, and values like this: doc['mydocument']['@has'] # == u'an attribute' doc['mydocument']['and']['many'] # == [u'elements', u'more elements'] doc['mydocument']['plus']['@a'] # == u'complex' doc['mydocument']['plus']['#text'] # == u'element as well' xmltodict also lets you roundtrip back to XML with the unparse function, has a streaming mode suitable for handling files that donโ€™t fit in memory, and supports XML namespaces.
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ reading-and-writing-xml-files-in-python
Reading and Writing XML Files in Python
November 30, 2017 - The function returns a document, which can be handled as an XML type. Thus, we can use the function getElementByTagName() to find a specific tag. Since each node can be treated as an object, we can access the attributes and text of an element using the properties of the object.
๐ŸŒ
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.