FormatterHQ

XML to String Converter

Turn an XML document into a ready-to-paste string literal with quotes, backslashes and newlines escaped, on one line or as concatenated lines.

Input XML
Output TEXT
Ready.

How to use the XML to String Converter

  1. Paste your XML or upload a file.
  2. Choose Output: Single-line string or Concatenated lines, and the Quotes style your language uses.
  3. Keep Minify first ticked for the shortest literal, or untick it to preserve indentation and comments.
  4. Click Convert to String and copy the literal into your code.

Convert XML to string literals for your code

Unit tests, mock servers and API clients often need an XML payload inside source code. Pasting it between quotes breaks immediately: every " in an attribute ends the string, and every newline is a syntax error. This XML to string converter escapes the document into a literal you can paste straight into Java, C#, JavaScript, TypeScript or Python, or use as a JSON string value.

Example

<user id="7">
  <!-- test -->
  <name>O'Neil "Pat"</name>
  <path>C:\temp</path>
</user>

With the defaults (single-line, double quotes, Minify first):

"<user id=\"7\"><name>O'Neil \"Pat\"</name><path>C:\\temp</path></user>"

With Minify first off and Output set to Concatenated lines:

"<user id=\"7\">\n" +
"  <!-- test -->\n" +
"  <name>O'Neil \"Pat\"</name>\n" +
"  <path>C:\\temp</path>\n" +
"</user>"

What each option does

  • Output: Single-line string – one literal; line breaks become \n.
  • Output: Concatenated lines – one quoted piece per line joined with +, which keeps long payloads readable in code review.
  • Quotes – double quotes escape " as \"; single quotes escape ' as \' and leave double quotes alone, which suits XML full of attribute quotes.
  • Minify first – removes indentation, line breaks and comments before escaping. Untick it to keep the document exactly as written.

In every mode, backslashes are doubled and tab characters become \t. Non-ASCII characters such as é are left as they are.

Language notes

  • Java and C# – use double quotes. Concatenated lines compile as written. Modern alternatives are Java text blocks and C# raw string literals, which need no escaping at all.
  • JavaScript and TypeScript – either quote style works; single quotes give the cleanest result for attribute-heavy XML.
  • Python – both quote styles work. For concatenated lines, wrap the whole expression in parentheses, because a line ending in + is not a continuation on its own.
  • JSON – use double quotes and single-line output; JSON strings cannot use single quotes or +.

Text blocks and raw strings still need care

Newer language features reduce escaping, but they do not all remove it. Take the example document again:

String xml = """
    <user id="7">
      <name>O'Neil "Pat"</name>
      <path>C:\\temp</path>
    </user>
    """;

In a Java text block the quotes are fine, but escape sequences are still processed, so C:\temp must be written with a doubled backslash; a single one would turn \t into a tab. Python's triple-quoted strings behave the same way unless you add the r prefix. C# raw string literals ("""…""") are the exception and take the XML completely as written. When in doubt, the escaped output from this tool is the form that works in every version.

String versus entity escaping

This tool escapes for a programming language, not for XML. If you need to put markup inside another XML document, where < must become &lt;, use XML escape instead. To only compact the document without quoting it, use XML minify. The same job for JSON payloads is done by JSON stringify.

Convert XML to a string in Python

To turn an ElementTree document into a string in Python, call ET.tostring() with encoding="unicode". Without that argument the function returns bytes, which is the usual surprise: joining the result to text raises TypeError, and printing it shows a b'...' wrapper. When you need the XML as an escaped literal for source code or a JSON value, json.dumps() adds the quotes and backslashes, and ensure_ascii=False keeps accented characters readable.

import json
import xml.etree.ElementTree as ET

root = ET.Element("user", id="7")
ET.SubElement(root, "name").text = "O'Neil"
ET.SubElement(root, "path").text = r"C:\temp"

as_bytes = ET.tostring(root)                      # default: bytes
as_text = ET.tostring(root, encoding="unicode")   # str
print(type(as_bytes).__name__, type(as_text).__name__)
print(as_text)

# An escaped literal for source code or a JSON value
print(json.dumps(as_text, ensure_ascii=False))

The last line it prints is identical to what the converter above returns for the same document with the default settings, which is the quicker route when the XML is already on your clipboard.

Frequently asked questions

Why does the output lose my comments?
Minify first removes comments along with indentation. Untick Minify first to keep comments and the original line structure in the string.
Which quote style should I choose?
Use the quote character your language requires for normal strings. If the language accepts both, single quotes are often cleaner for XML because attribute values in double quotes then need no escaping.
Does it escape < and > as &lt; and &gt;?
No, and it should not for a code literal: the string must contain the real XML. Entity escaping is a different task, handled by the XML escape tool.
How do I turn the string back into XML?
Evaluate or print the string in your language, or paste the value without the surrounding quotes into an unescape tool for that language, then format the result with an XML formatter.

Last updated October 3, 2026

Related tools

JSON to String Converter Convert JSON to a single escaped string you can paste into code, databases or other JSON documents. Choose double, single or no quotes. String to JSON Converter Convert an escaped JSON string back into formatted JSON. Handles quoted literals, backslash-escaped text and double-encoded JSON. JSON Multiline String Converter Convert multi-line text into a valid JSON string with \n escapes, a JSON array of lines, or concatenated string literals. Reverse String Reverse text by characters, words or lines, or flip the letters of each word individually. String Builder Turn multi-line text into StringBuilder / string concatenation code for Java, C#, JavaScript, Python, PHP or Go. String Byte Size Counter Count how many bytes a string uses in UTF-8, UTF-16 and UTF-32, plus characters, code points and Base64/URL-encoded size. XML Validator Validate XML online for well-formedness. Find unclosed tags, bad nesting and invalid characters with exact line and column numbers. XML Viewer View XML as a collapsible tree alongside formatted text. Inspect elements, attributes and values in any XML document. XML XSL Transform Apply an XSLT stylesheet to XML online and preview the result. Produce HTML, XML or text output from any XML document. XPath Tester Test XPath expressions online against your XML. See matched nodes, attributes, strings, numbers or booleans instantly. MXML Viewer View and format Adobe Flex / Apache Royale MXML files online with a component tree and neatly indented markup. OPML Viewer View OPML subscription lists and outlines as a clickable, nested list. Inspect feed URLs exported from any RSS reader.