Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsFor ordinary text, create an XML element, assign the string to its .text property, and serialize it with xml.etree.ElementTree.tostring(). The serializer escapes characters such as & and < in the right context. Use encoding="unicode" when you need the result as a Python str rather than bytes.
Convert a Python string into XML text
This example turns a Python value into the text content of a <message> element:
import xml.etree.ElementTree as ET
root = ET.Element("message")
root.text = "Use <, &, and > safely"
xml_text = ET.tostring(root, encoding="unicode")
print(xml_text)
The result is XML markup, with text characters escaped for XML, such as < and &. The value remains text inside the element; it does not become nested XML elements. ElementTree provides an API for creating and parsing XML data, as documented in the Python ElementTree documentation.
Put the string in an XML attribute
When the value belongs in an attribute rather than between an element’s tags, assign it through the element’s attribute mapping. Serialization then handles escaping in the attribute context:
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware match#1 Best Overall
import xml.etree.ElementTree as ET
item = ET.Element("item", {"label": 'A & B "special"'})
xml_text = ET.tostring(item, encoding="unicode")
print(xml_text)
For manually assembling an attribute value, xml.sax.saxutils.quoteattr() prepares the value with suitable quoting and escaping. The narrower escape() helper is for text content and does not itself quote an attribute value. See the Python SAX utilities documentation.
Choose the right operation for what the string contains
- Plain data for an element: create an element, assign the value to
.text, and serialize. - Plain data for an attribute: set the attribute on the element, then serialize.
- Existing XML markup: use
ET.fromstring()to parse it into an Element when you need an XML tree. - A text fragment to escape manually:
xml.sax.saxutils.escape()replaces&,<, and>. It is a limited escaping helper, not a document generator.
Do not insert a string as raw markup just because it contains angle brackets. Decide whether it represents plain text or already-formed XML: serialization writes a tree as markup, while parsing turns markup into a tree. ElementTree’s tutorial covers creating and parsing XML.
Rank #2
Get a string or encoded bytes from tostring()
ET.tostring(element) returns bytes by default, using the us-ascii encoding. Pass encoding="unicode" for a Python string, or specify an encoding such as "utf-8" when you need encoded bytes:
xml_text = ET.tostring(root, encoding="unicode") # str
xml_bytes = ET.tostring(root, encoding="utf-8") # bytes
Match the result to its destination: text streams accept strings, while binary streams accept bytes. Do not assume serialization always returns a string.
Recommended Free Tools
Common conversion mistakes
- Escaping manually in the wrong order: replacing ampersands after introducing entity references can turn
<into&lt;. Prefer element construction and serialization. - Using text escaping for an attribute:
escape()does not provide the attribute quoting step. Use ElementTree attributes orquoteattr()for manually assembled markup. - Confusing parsing and serialization:
fromstring()parses markup;tostring()serializes an Element. - Mixing strings and bytes: select the output type that matches the stream or API receiving it.
Parsing XML from an untrusted source
Turning ordinary data into XML with ElementTree is different from parsing XML supplied by an untrusted party. Python notes that XML features can create security concerns, including denial of service and local-file or network-related risks in some settings. Parser behavior depends on the Expat version and build configuration; consult the current Python XML processing guidance and check pyexpat.EXPAT_VERSION for the deployment in question.
When canonical XML is required
Ordinary serialization is sufficient for routine XML output. If a consuming protocol specifically requires canonical output—for example, for byte comparisons or digital signatures—Python documents ElementTree.canonicalize() as a C14N 2.0 transformation. Use it only when that requirement applies; canonicalization is not a substitute for constructing and serializing the XML tree. See the Python 3.12 ElementTree documentation.
Quick Recap
Best Value
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




