How can I escape double quotes in XML attributes values?

Xml

Xml Problem Overview


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?

Xml Solutions


Solution 1 - Xml

You can use &quot;

Solution 2 - Xml

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;".

Solution 3 - Xml

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

Solution 4 - Xml

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJader DiasView Question on Stackoverflow
Solution 1 - XmlSachin ShanbhagView Answer on Stackoverflow
Solution 2 - XmlWim CoenenView Answer on Stackoverflow
Solution 3 - XmlkjhughesView Answer on Stackoverflow
Solution 4 - XmlKenny EvittView Answer on Stackoverflow