วันพฤหัสบดีที่ 13 มกราคม พ.ศ. 2554

XmlTextWriter to format out xml with newline and indent.

This is sample from my project to serializer object with utf8.

XmlSerializer xmlFormat = new XmlSerializer( typeof( LeaveObjectItem ) );

string xml = String.Empty;

Encoding utf8EncodingWithNoByteOrderMark = new UTF8Encoding( false );
using (MemoryStream stream = new MemoryStream())
{
XmlTextWriter xtw = new XmlTextWriter( stream, utf8EncodingWithNoByteOrderMark );
xtw.Formatting = Formatting.Indented;
xtw.Indentation = 4;
xmlFormat.Serialize( xtw, ItemToExport );
xml = Encoding.UTF8.GetString( stream.ToArray() );
}

using (StreamWriter outfile =
new StreamWriter( fullpath, false, System.Text.Encoding.UTF8 ))
{
outfile.Write( xml.Replace( ">�<", ">DBNULL<" ) );
}

ไม่มีความคิดเห็น: