44

How can I put an & symbol in an attribute of an XML tag while keeping the XML valid?

<?xml version="1.0" ?> 
<a text="b&c"/>

When I use W3School's validator, I get the error:

EntityRef: expecting ';'

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
nagy.zsolt.hun
  • 6,292
  • 12
  • 56
  • 95
  • Related post - [How to escape "&" in XML?](https://stackoverflow.com/q/12524908/465053) – RBT Sep 02 '21 at 04:32

3 Answers3

81

Use a character reference to represent it: &amp;

See the specification:

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 3
    i like this answer better than other answers on other questions because it quotes the spec and i was able to escape all potential chars instead of just OP's one char – RozzA Jun 11 '16 at 22:46
11

You can use these escape sequences :

< (less-than)                   -   &#60; or &lt;

> (greater-than)                -   &#62; or  &gt;

& (ampersand)                   -   &#38;

' (apostrophe or single quote)  -   &#39;

" (double-quote)                -   &#34;
Shubham
  • 111
  • 1
  • 4
  • [Here's a link](https://www.dvteclipse.com/documentation/svlinter/How_to_use_special_characters_in_XML.3F.html) to more reading on these escape sequences. – Joseph316 Aug 30 '21 at 19:09
1
Re: XML and ampersand in links - not parsing
You should escape & with 

> Blockquote &amp; in an XML or HTML document.
Prince Kumar
  • 136
  • 4