182

From the following trials

<tag attr="\"">
<tag attr="<![CDATA["]]>">
<tag attr='"'>

Only the last one works for an XML parser that I'm using here. Is there an alternative?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jader Dias
  • 88,211
  • 155
  • 421
  • 625
  • 2
    **`"`** is the answer; [**here's the explanation**](https://stackoverflow.com/a/47534887/290085). – kjhughes May 13 '18 at 18:31
  • 1
    Possible duplicate: *[What characters do I need to escape in XML documents?](https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents)* – Peter Mortensen May 20 '20 at 17:17

4 Answers4

285

You can use &quot;

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
60

From the XML specification:

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "&apos;", and the double-quote character (") as "&quot;".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
39

A double quote character (") can be escaped as &quot;, but here's the rest of the story...

Double quote character must be escaped in this context:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Double quote character need not be escaped in most contexts:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Similarly, (') require no escaping if (") are used for the attribute value delimiters:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

See also

kjhughes
  • 106,133
  • 27
  • 181
  • 240
8

The String conversion page on the Coder's Toolbox site is handy for encoding more than a small amount of HTML or XML code for inclusion as a value in an XML element.

Kenny Evitt
  • 9,291
  • 5
  • 65
  • 93