What characters must be escaped in XML documents, or where could I find such a list?
What characters must be escaped in XML documents, or where could I find such a list?
If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation.
There are only five:
" "
' '
< <
> >
& &
Escaping characters depends on where the special character is used.
The examples can be validated at the W3C Markup Validation Service.
The safe way is to escape all five characters in text. However, the three characters ", ' and > needn't be escaped in text:
<?xml version="1.0"?>
<valid>"'></valid>
The safe way is to escape all five characters in attributes. However, the > character needn't be escaped in attributes:
<?xml version="1.0"?>
<valid attribute=">"/>
The ' character needn't be escaped in attributes if the quotes are ":
<?xml version="1.0"?>
<valid attribute="'"/>
Likewise, the " needn't be escaped in attributes if the quotes are ':
<?xml version="1.0"?>
<valid attribute='"'/>
All five special characters must not be escaped in comments:
<?xml version="1.0"?>
<valid>
<!-- "'<>& -->
</valid>
All five special characters must not be escaped in CDATA sections:
<?xml version="1.0"?>
<valid>
<![CDATA["'<>&]]>
</valid>
All five special characters must not be escaped in XML processing instructions:
<?xml version="1.0"?>
<?process <"'&> ?>
<valid/>
HTML has its own set of escape codes which cover a lot more characters.
Perhaps this will help:
List of XML and HTML character entity references:
In SGML, HTML and XML documents, the logical constructs known as character data and attribute values consist of sequences of characters, in which each character can manifest directly (representing itself), or can be represented by a series of characters called a character reference, of which there are two types: a numeric character reference and a character entity reference. This article lists the character entity references that are valid in HTML and XML documents.
That article lists the following five predefined XML entities:
quot "
amp &
apos '
lt <
gt >
New, simplified answer to an old, commonly asked question...
Always (90% important to remember)
Attribute Values (9% important to remember)
attr=" 'Single quotes' are ok within double quotes."attr=' "Double quotes" are ok within single quotes.'" as " and ' as ' otherwise.Comments, CDATA, and Processing Instructions (0.9% important to remember)
Esoterica (0.1% important to remember)
]]> as ]]> unless ]]> is ending a CDATA section. The accepted answer is not correct. Best is to use a library for escaping xml.
As mentioned in this other question
"Basically, the control characters and characters out of the Unicode ranges are not allowed. This means also that calling for example the character entity is forbidden."
If you only escape the five characters. You can have problems like An invalid XML character (Unicode: 0xc) was found