Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retain CDATA tags when storing query results in an Xml variable?

When I generate Xml in Sql Server 2008 R2 using For Explicit (because my consumer wants one of the elements wrapped in CDATA) and store the results in an Xml variable, the data I want wrapped in CDATA tags no longer appears wrapped in CDATA tags. If I don't push the For Xml Explicit results into an Xml variable then the CDATA tags are retained. I am using the @Xml variable as an SqlParameter from .Net.

In this example, the first select (Select @Xml) does not have Line2 wrapped in CDATA tags. But the second select (the same query used to populate the @Xml variable) does have the CDATA tags wrapping the Line2 column.

Declare @Xml Xml

Begin Try
    Drop Table #MyTempTable
End Try
Begin Catch
End Catch

Select
    'Record' As Record
    , 'Line1' As Line1
    , 'Line2' As Line2
Into
    #MyTempTable

Select @Xml =
(
    Select
        x.Tag
        , x.Parent
        , x.[Root!1]
        , x.[Record!2!Line1!Element]
        , x.[Record!2!Line2!cdata]
    From
        (
            Select
                1 As Tag, Null As Parent
                , Null As [Root!1]
                , Null As [Record!2!Line1!Element]
                , Null As [Record!2!Line2!cdata]
            From
                #MyTempTable
            Union
            Select
                2 As Tag, 1 As Parent
                , Null As [Root!1]
                , Line1 As [Record!2!Line1!Element]
                , Line2 As [Record!2!Line2!cdata]
            From
                #MyTempTable
        ) x
    For
        Xml Explicit
)

Select @Xml

    Select
        x.Tag
        , x.Parent
        , x.[Root!1]
        , x.[Record!2!Line1!Element]
        , x.[Record!2!Line2!cdata]
    From
        (
            Select
                1 As Tag, Null As Parent
                , Null As [Root!1]
                , Null As [Record!2!Line1!Element]
                , Null As [Record!2!Line2!cdata]
            From
                #MyTempTable
            Union
            Select
                2 As Tag, 1 As Parent
                , Null As [Root!1]
                , Line1 As [Record!2!Line1!Element]
                , Line2 As [Record!2!Line2!cdata]
            From
                #MyTempTable
        ) x
    For
        Xml Explicit

Begin Try
    Drop Table #MyTempTable
End Try
Begin Catch
End Catch
like image 810
Mavyak Avatar asked Feb 03 '12 16:02

Mavyak


1 Answers

You can't. The XML data type does not preserve CDATA sections.

Have a look here for a discussion about the subject.

http://social.msdn.microsoft.com/forums/en-US/sqlxml/thread/e22efff3-192e-468e-b173-ced52ada857f/

like image 187
Mikael Eriksson Avatar answered Oct 05 '22 01:10

Mikael Eriksson