SQL Server 2012: Hierarchical XML data - escape characters

后端 未结 1 1216
你的背包
你的背包 2020-12-21 23:46

I\'m trying to create XML format output from the below hierarchical data. In the output I\'m seeing escape characters (<,\",> replaced with escape characters).

B

相关标签:
1条回答
  • 2020-12-22 00:20

    Your problems:

    1. You try to use the output of SelectChild, which is of type XML, as the content of the attribute @ListDirectChildren. You cannot use XML in this place, therefore it is handled (and escaped) as normal text. Are you attempting to create kind of a recursive child list?

    2. In your outer query you cast the XML to VARCHAR(MAX) (btw: use always NVARCHAR in connction with XML). Again you'll force the engine to treat this text as text and therefore escape it.

    3. You try to add the string "null" to express the missing of a value. But XML works differently: a. The element is missing in the XML completely: Querying it will return NULL, that's fine.

      b. For some rules the Element must be there, but should be empty:
      <ListDirectChildren></ListDirectChildren> or <ListDirectChildren /> (which is meaning exactly the same). Query the node's text() and you get NULL, that's fine too.

      c. For some rules you want to mark the element as NULL. Use XSINIL

    Try this for variations of empty and null:

    DECLARE @x XML=
    '<root>
       <testempty1 />
       <testempty2></testempty2>
     </root>';
    
    SELECT @x.value('(/root/testempty1)[1]','nvarchar(max)') AS testempty1_Content
          ,@x.value('(/root/testempty1/text())[1]','nvarchar(max)') AS testempty1_Text
          ,@x.value('(/root/testempty2)[1]','nvarchar(max)') AS testempty2_Content
          ,@x.value('(/root/testempty2/text())[1]','nvarchar(max)') AS testempty2_Text
          ,@x.value('(/root/NotExistingElement)[1]','nvarchar(max)') AS NotExistingElement_Content
          ,@x.value('(/root/NotExistingElement/text())[1]','nvarchar(max)') AS NotExistingElement_Text
    

    The result:

                       Content  Text
    testempty1         ""       NULL
    testempty2         ""       NULL
    NotExistingElement NULL     NULL
    

    Try this for XSINIL

    SELECT NULL AS test FOR XML RAW, ELEMENTS XSINIL
    

    to get this

    <row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <test xsi:nil="true" />
    </row>
    

    My suggestion:

    This question

    Can someone please suggest me how to address the escape characters?

    is hopefully solved. Please start a new question where you add some more data to your sample scenario to reflect multiple children, place a link to this question and state the expected output (how the XML should look like).

    0 讨论(0)
提交回复
热议问题