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
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?
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.
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
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
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>
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).