Wrapping and removing CDATA around XML

后端 未结 2 1998
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 08:01

This is my xml. My goal is to wrap the data inside the Value node with CDATA on an export and then import that back into an Xml type column with the CDATA removed.

2条回答
  •  时光说笑
    2020-12-22 08:25

    If you really need the CDATA section within your XML, there are only two options

    • string concatenation (very bad)
    • FOR XML EXPLICIT (in this case you've got the answer from Pawel)

    But you should take into consideration, that the CDATA section exists for lazy input only. There is absolutely no difference whether the content is enclosed as CDATA section or properly escaped. Therefore Microsoft decided not even to support the CDATA syntax in modern XML methods. It is just not needed.

    Look at these examples:

    --I start with a string containing the same content escaped and in CDATA

    DECLARE @s VARCHAR(500)=
    '
    Normal Text
    Text with forbidden character & <>
    ]]>
    ';
    

    --This string is casted to XML.

    DECLARE @x XML=CAST(@s AS XML);
    

    --This is the output, and you can see, that the CDATA section is encoded an no CDATA any more. CDATA will always be replaced by a valid escaped string:

    SELECT @x;
    
    
      Normal Text
      Text with forbidden character & <>
      Text with forbidden character & <>
    
    

    --The back-cast shows clearly, that the XML internally has no CDATA any more

    SELECT CAST(@x AS VARCHAR(500));
    
    
       Normal Text
       Text with forbidden character & <>
       Text with forbidden character & <>
    
    

    --Reading the nodes one-by-one shows the correct content anyway

    SELECT a.value('.','varchar(max)')
    FROM @x.nodes('/root/a') AS A(a)
    
    Normal Text
    Text with forbidden character & <>
    Text with forbidden character & <>
    

    The only reason to use CDATA and to insist, that this must be included into the XML's text representation (which is not the XML!) are third party or legacy requirements.

    And keep in mind: If you use string concatenation, you can store the XML with a readable CDATA in a string format only. Whenever you cast this to XML the CDATA will be ommited. Using FOR XML EXPLICIT allows the typesafe storage, but is very clumsy with deeper nestings. This might be OK with an external interface, but you should think twice about this...

    Two links to related answers (by me :-) ):

    • https://stackoverflow.com/a/38547537/5089204
    • https://stackoverflow.com/a/38225963/5089204

提交回复
热议问题