XML serialization and UTF encoding 8

P

piku

I am trying to generate XML file with UTF encoding 8 ,
But after serliazation the xml is generated as
<?xml version=\"1.0\" encoding=\"utf-16\"?>
I want UTF encoding 8 .

How can I achieve that.

The current Code is
Code:
IDA idaEntity = new IDA ();
idaEntity.First_Name ="abc";
idaEntity.Last_Name ="def";
idaEntity.Address_Line1 ="123456";
idaEntity.Address_Line2 ="";
idaEntity.City ="abcdef";
idaEntity.State ="AA";
idaEntity.Zip_Code ="12345";
idaEntity.Home_Phone ="1234567890";
idaEntity.Work_Phone  ="";
idaEntity.SSN ="123456789";
idaEntity.Customer_ID = "1234567";
idaEntity.Order_ID= "98765432";

StringBuilder sb = new  StringBuilder  ();

XmlSerializer addSerializer = new XmlSerializer(typeof(IDA));

XmlTextWriter writer = new   XmlTextWriter( new StringWriter (sb) );
writer.Formatting = Formatting.None;
addSerializer.Serialize(writer, idaEntity);
Console.WriteLine(sb);

The output I am getting is

[OUTPUT]
<?xml version="1.0" encoding="utf-16"?><IDA
xmlns:xsd="http://www.w3.org/2001/XM
LSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Customer_ID>50027961</Customer_ID><Order_ID>50027317</Order_ID><First_Name>abc
</First_Name><Last_Name>def</Last_Name><Address_Line1>123456</Address_Line1><Ad
dress_Line2
/><City>abcdef</City><State>AA</State><Zip_Code>12345</Zip_Code><
SSN>123456789</SSN><Home_Phone>1234567890</Home_Phone><Work_Phone
/></IDA>

[/OUTPUT]

How can I get encoding utf-8 instead of 16.

Thanks !
 
M

Martin Honnen

piku said:
I am trying to generate XML file with UTF encoding 8 ,
But after serliazation the xml is generated as
<?xml version=\"1.0\" encoding=\"utf-16\"?>
I want UTF encoding 8 .

How can I achieve that.

Serialize to a file or a stream, not to a string writer as a string is
always (internally) UTF-16 encoded.
 
J

Jon Skeet [C# MVP]

Martin Honnen said:
Serialize to a file or a stream, not to a string writer as a string is
always (internally) UTF-16 encoded.

However, you can still make a StringWriter expose its encoding as UTF-8
by overriding its properties.

It so happens I have a class which does exactly that in my utility
library :)
See http://www.pobox.com/~skeet/csharp/miscutil
and look at MiscUtil.IO.StringWriterWithEncoding
 
S

Samuel R. Neff

Use a MemoryStream and StreamWriter and in the constructor to the
StreamWriter you can specify the encoding to use.

HTH,

Sam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top