October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Convert a String to XML in Python: Text, Attributes, and Safe Serialization

Use Python’s ElementTree to place a string in XML text or an attribute, then serialize it safely as a string or bytes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For 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 &lt; and &amp;. 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:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common conversion mistakes

  • Escaping manually in the wrong order: replacing ampersands after introducing entity references can turn &lt; into &amp;lt;. Prefer element construction and serialization.
  • Using text escaping for an attribute: escape() does not provide the attribute quoting step. Use ElementTree attributes or quoteattr() 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.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.