How do I escape double quotes in attributes in an XML String in T-SQL?

XmlTsqlEscaping

Xml Problem Overview


Pretty simple question - I have an attribute that I would like to have double quotes in. How do I escape them? I've tried

  • "
  • ""
  • \"

And I've made the @xml variable both xml type and varchar(max) for all of them.

 declare @xml xml --(or varchar(max) tried both)
 
 set @xml = '<transaction><item value="hi "mom" lol" 
 	ItemId="106"  ItemType="2"  instanceId="215923801"  dataSetId="1" /></transaction>'
 
 declare @xh int
 exec sp_xml_preparedocument @xh OUTPUT, @xml
 
 insert into @commits --I declare the table, just removed it for brevity
 select
 	x.*
 from openxml(@xh,'/transaction/item')
  WITH (
 	dataItemId int,
     dataItemType int,
 	instanceId int,
 	dataSetId int,
 	value varchar(max)
  ) x

Xml Solutions


Solution 1 - Xml

Wouldn't that be &quot; in xml? i.e.

"hi &quot;mom&quot; lol" 

**edit: ** tested; works fine:

declare @xml xml

 set @xml = '<transaction><item value="hi &quot;mom&quot; lol" 
    ItemId="106"  ItemType="2"  instanceId="215923801"  dataSetId="1" /></transaction>'

select @xml.value('(//item/@value)[1]','varchar(50)')

Solution 2 - Xml

tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:

declare @xml xml 
set @xml = "<transaction><item value=""hi"" /></transaction>"

If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:

declare @xml xml
set @xml = "<transaction><item value=""hi &quot;mom&quot; lol"" /></transaction>"

Solution 3 - Xml

Cannot comment anymore but voted it up and wanted to let folks know that &quot; works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src=&quot;(.*)&quot;.*" using the escaped version instead of double-quotes.

Solution 4 - Xml

In Jelly.core to test a literal string one would use:

&lt;core:when test="${ name == 'ABC' }"&gt; 

But if I have to check for string "Toy's R Us":

&lt;core:when test="${ name == &amp;quot;Toy&apos;s R Us&amp;quot; }"&gt;

It would be like this, if the double quotes were allowed inside:

&lt;core:when test="${ name == "Toy's R Us" }"&gt; 

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
QuestionTom RitterView Question on Stackoverflow
Solution 1 - XmlMarc GravellView Answer on Stackoverflow
Solution 2 - XmlJoel CoehoornView Answer on Stackoverflow
Solution 3 - XmlpulkitsinghalView Answer on Stackoverflow
Solution 4 - XmlMarkView Answer on Stackoverflow