How to encode and escape an apostrophe in XML
Learn when an apostrophe must be escaped in XML, which codes to use (', ', '), and how to escape it safely and verify the result.
What escaping an apostrophe in XML does
In XML, the straight apostrophe (', Unicode U+0027) is also one of the two characters that can delimit an attribute value. Escaping replaces the character with a reference, which is a short code that the XML parser turns back into the apostrophe when it reads the file. The input is ordinary text that contains apostrophes. The output is the same text with the apostrophes, and any other markup-sensitive characters, written as references. Once the file is parsed, the value is unchanged. The only effect is that the parser no longer mistakes the apostrophe for the end of a quoted value.
Apostrophe codes you can use in XML
| Form | Written as | Notes |
| Predefined entity | ' | One of the five entities built into XML. HTML 4 does not define it, so prefer a numeric reference if the same text may be read as legacy HTML. |
| Decimal character reference | ' | Represents U+0027 and works in any XML document. |
| Hexadecimal character reference | ' | The same character in hexadecimal notation. |
| Typographic apostrophe (right single quotation mark, U+2019) | ’ or ’ | A different character from the straight apostrophe. It never needs escaping, but these references are useful when the file's encoding cannot represent it. |
When the apostrophe actually needs escaping
- Attribute value enclosed in single quotes: escaping is required. An unescaped apostrophe ends the value early, and the document becomes malformed.
- Attribute value enclosed in double quotes: escaping is optional. A literal apostrophe is valid.
- Element text content: escaping is optional. A literal apostrophe is valid.
- CDATA sections: do not escape. References are not interpreted inside CDATA, so ' would remain literal text.
- Comments and processing instructions: references are not expanded there either, so write the apostrophe literally.
The apostrophe is rarely the only character to handle. In text and attribute values, & and < must always be escaped as & and < (except inside CDATA). The sequence ]]> in text needs > written as >, and a double quote inside a double-quoted attribute needs ". When you replace characters by hand, replace & first. Otherwise the & at the start of each new reference gets escaped again, and ' turns into '.
How to escape apostrophes step by step
- 1. Work on a copy of the file or text so you can compare it with the original or roll back.
- 2. Check whether the content is already escaped. Search it for existing references such as & or '. Escaping already-escaped text produces double escaping.
- 3. Identify where the text will go: element content, a single-quoted attribute, a double-quoted attribute or a CDATA section. This tells you which characters must be escaped.
- 4. If you are generating XML from code, prefer an XML library or serializer. It escapes whatever its chosen quoting style requires.
- 5. If you must do a plain find-and-replace, run it on raw text only, never on a finished XML file. Replace & first, then <, > and the apostrophe or double quote as needed.
- 6. Parse the result with an XML parser and confirm that the decoded value matches the original text.
Example: escaping with a library (Python)
Python's standard xml.sax.saxutils module escapes only &, < and > by default. You pass an extra mapping to have it escape the apostrophe as well. Its quoteattr function chooses a quote style for an attribute value and escapes accordingly. The comments in the illustrative snippet below show the output these functions are documented to produce. Run the snippet yourself to confirm the output in your environment.
from xml.sax.saxutils import escape, quoteattr
text = "Rock 'n' roll & blues"
print(escape(text, {"'": "'"}))
# Rock 'n' roll & blues
print(quoteattr("It's here"))
# "It's here" (wrapped in double quotes, so the apostrophe stays literal)
Example: escaping raw text on the command line (sed)
For a plain list of values that you will insert into XML, sed can do the replacement. In a sed replacement, a bare & means "the matched text," so each & that starts a reference must be written as &. The & rule comes first so that later replacements are not escaped twice. Do not run this on an existing XML file, because it would also escape the markup's own < and > characters.
sed -e 's/&/\&/g' \
-e 's/</\</g' \
-e 's/>/\>/g' \
-e "s/'/\'/g" \
input.txt > escaped.txt
Before-and-after example
Illustrative example: in the first line, the apostrophe in the single-quoted attribute ends the value early, so the line is malformed. The second line escapes it. The third line avoids the problem by using double quotes. In all three lines, the apostrophe in the element text can stay literal.
Before (malformed):
<note title='Editor's draft'>It's ready</note>
After (escaped):
<note title='Editor's draft'>It's ready</note>
Alternative (double-quoted attribute):
<note title="Editor's draft">It's ready</note>
Check the result
A parser check confirms two things: that the file is well-formed, and that the escaped value decodes back to the original text. xmllint, part of the libxml2 tools, prints nothing when a file parses cleanly and prints an error otherwise. Python's ElementTree can print the decoded attribute value. For the example above, the expected value is Editor's draft, with a literal apostrophe. A final search for ' or & catches double escaping.
xmllint --noout note.xml
python3 -c "import xml.etree.ElementTree as ET; print(ET.parse('note.xml').getroot().get('title'))"
grep -n -e '&apos;' -e '&amp;' note.xml
If the check fails, restore your copy and redo the escaping. When you edit in place with GNU sed, sed -i.bak keeps the original as a .bak file. If you find double escaping, restore from the copy rather than reversing it with another find-and-replace. A reverse replacement can also change text that legitimately contained the characters &.
Straight versus curly apostrophes and file encoding
Escaping does not change which apostrophe your text contains. The straight apostrophe (') and the typographic apostrophe (’, U+2019) are separate characters. Only the straight one can conflict with attribute delimiters. A curly apostrophe can be written literally as long as the file is saved in the encoding it declares (UTF-8 is the default when no encoding is declared). If the file uses an encoding that cannot represent the character, write it as ’ instead. Converting one apostrophe style into the other changes the content, so do it only when that is what you want.
Note on scope: no tool-specific documentation or test results were supplied for this guide. The rules above follow the XML 1.0 specification. The code samples are illustrative and have not been run as part of this guide, so check them against the documentation for your library or command-line tool.