Alex Rivera | Logout

When is it required to escape characters in XML?

Asked 2011-08-01T12:15:12.850
14

When should we replace < > & " ' in XML to characters like &lt etc.

My understanding is that it's just to make sure that if the content part of XML has > < the parser will not treat is start or end of a tag.

Also, if I have a XML like:

<hello>mor>ning<hello>

should this be replaced to either:

  • &lthello&gtmor&gtning&lthello&gt
  • &lthello&gtmor>ning&lthello&gt
  • <hello>mor&gtning<hello>

I don't understand why replacing is needed. When exactly is it required and what exactly (tags or text) should be replaced?

Edit
Report

1 Answer

11

Section 2.4 of the XML Specification clearly states:

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " &amp; " and " &lt; " respectively. The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility, be escaped using either " &gt; " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

answered 2011-08-01T12:22:09.847

Your Answer