You should not think about XML as text with some fancy extras... How is this stored in SQL Server? If the target column is a real XML type you should not bother about the visual format at all. If the visual format is of any importance, than it is the problem of the consuming / reading software...
If you store the XML in a string typed column, you can store literally everything, even invalid XML. If you want to use this XML in SQL Server with XML methods like .value()
or .nodes()
you will need the real XML type... If you can control this, make sure the target is a real XML typed variable or column!
The xml declaration (the processing instruction stating the encoding and the xml-version in most cases) will be ommitted in any case. SQL Server does not accept such a declaration with its native XML type.
You get into troubles, if you store the XML in a string typed column together with an xml declaration. In this case you should use encoding="utf-16"
and you must store this in a NVARCHAR(MAX)
column.
If the actual encoding is NCHAR
or NVARCHAR
SQL Server expects a unicode encoded string. If the column is without the N
, SQL Server expects extended ASCII (collation dependant). You cannot mix this! You cannot convert a string with an xml-declaration stating utf-16
if it is a VARCHAR
(and vice-versa).
Anyway one should avoid ASCII
encoded XML. This will get you into troubles with non-latin characters and will need expensive operations due to the fact, that SQL Server stores XML in a unicode based tree structure internally.
About namespaces, if there are any, you must be very carefull. They must be part of the XML, otherwise you won't be able to read the XML later.
In this answer you find the code to convert an XDocument
into XmlDocument
. Then use the property OuterXml
to get the textual representation of the XML. As C# internally uses unicode strings, just pass this over into a variable or column of type XML
or NVARCHAR(MAX)
.