My nvarchar value contains a control character - Start of Text (0x0002 / STX). I would like to include this in my XML value. Now I know XML is not tolerant of control characters so the only way I can come up with is to include it as  (normally it should be  but XML does not like this). A side effect of doing this the way I am doing it is that normal characters get double-escaped, e.g. & becomes &.
Is there an easy way to include this character, and any other possible control characters in my XML value without having normal characters double-escaped? It doesn't have to even be as , I'd be just as happy with 0x0002, for example.
DECLARE @Data table (String nvarchar(max));
INSERT INTO @Data (String)
VALUES ('& hi');
--I'd like this to output <Test>&#x02;& hi</Test> or similar
SELECT CAST ((SELECT (SELECT String AS [*] FOR XML PATH(''))
FROM @Data
FOR XML PATH('Test')) AS XML)
xmltype or can it remainnvarchar? If the latter, it's pretty simple, your code is overcomplicated dbfiddle.uk/w-2AMwgh the former remains not allowed, as noted in the docs learn.microsoft.com/en-us/sql/relational-databases/xml/…