Search code examples
c#sql-serverxmlutf-8utf-16

How convert xml string UTF8 to UTF16?


I have a string of XML(utf-8).I need to store the string in the database(MS SQL). Encoding a string must be UTF-16.

This code does not work, utf16Xml is empty

XDocument xDoc = XDocument.Parse(utf8Xml);
xDoc.Declaration.Encoding = "utf-16";
StringWriter writer = new StringWriter();
XmlWriter xml = XmlWriter.Create(writer, new XmlWriterSettings() 
            { Encoding = writer.Encoding, Indent = true });

xDoc.WriteTo(xml);

string utf16Xml = writer.ToString();

utf8Xml - string contains a serialize object(encoding UTF8).

How convert xml string UTF8 to UTF16?


Solution

  • This might help you

    MemoryStream ms = new MemoryStream();
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.OmitXmlDeclaration = true;
            xws.Indent = true;
            XDocument xDoc = XDocument.Parse(utf8Xml);
            xDoc.Declaration.Encoding = "utf-16";
            using (XmlWriter xw = XmlWriter.Create(ms, xws))
            {
    
                xDoc.WriteTo(xw);
            }
            Encoding ut8 = Encoding.UTF8;
            Encoding ut116 = Encoding.Unicode;
            byte[] utf16XmlArray = Encoding.Convert(ut8, ut116, ms.ToArray());
            var utf16Xml = Encoding.Unicode.GetString(utf16XmlArray);