Click here to Skip to main content
15,877,754 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I create a XML file. It took
<?xml version="1.0" encoding="utf-16" ?>
but I want
<?xml version="1.0" encoding="utf-8" ?>
How i convert it?

Here is my code.

I update my code. Now please look it. And warning msg is
DOMDocument::loadXML(): Document labelled UTF-16 but has UTF-8 content in Entity

XmlDocument xmlDoc = new XmlDocument();

XmlElement xmlElmdetails = xmlDoc.CreateElement("details");

XmlElement xmlName = xmlDoc.CreateElement("name");
xmlName.InnerText = "Jack";

XmlElement xmlPhone = xmlDoc.CreateElement("phone");

XmlElement xmlHome = xmlDoc.CreateElement("home");
xmlHome.InnerText = "9876543210";

 using (StringWriter sr = new StringWriter())
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.Indent = true;

                using (XmlWriter xtw = XmlTextWriter.Create(sr, xws))
Updated 20-May-14 2:06am

Use the XmlWriterSettings.Encodeing property to use the encoding you want:
    XmlWriterSettings xws = new XmlWriterSettings();
    xws.Indent = true;
    xws.Encoding = Encoding.UTF8;

    // ...
This will cause your application to write UTF-8 encoded XML.

But UTF-8 already is the mentioned property's standard value. So the question remains how the UTF-16 encoded XML arose in the first place.
Does your application create it or do you get it from somewhere?
Share this answer
The Encoding property only applies to the XmlWriter instances that are created either with the specified Stream or with the specified file name. If the XmlWriter instance is created with the specified TextWriter, the Encoding property is overridden by the encoding of the underlying TextWriter. For example, if this property is set to Unicode (UTF-16) for a particular XmlWriter, but the underlying writer is a StreamWriter (which derives from TextWriter) with its encoding set to UTF8, the output will be UTF-8 encoded.
String are utf-16 internally, so you have to change the encoding of your StringWriter...
Share this answer

What's that Response? Looks like some web thingy.
Does it have an Encoding property? If so, set it properly.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900