แสดงบทความที่มีป้ายกำกับ XmlSerializer แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ XmlSerializer แสดงบทความทั้งหมด

วันพฤหัสบดีที่ 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<" ) );
}

วันพุธที่ 28 เมษายน พ.ศ. 2553

Xml Serializer in memory.

My object name is request.
and I send TextReader parameter to ChargeRequestFactory Object
This explain simple 2 way to do about this.
But because StringWriter has alway create xml with utf 16 encoding
and I need UTF 8 instead so my choice is choose to use in second solution

Yes we can use StringWriter to create XML with UTF 8 but it must create new
Class and override Encoding so Second task look enough for me.

(1)
StringWriter stringWriter = new StringWriter();

xmlSerializer.Serialize( stringWriter, request );

StringReader stringReader = new StringReader( stringWriter.ToString() );

ChargeRequestFactory factory = new ChargeRequestFactory( stringReader );

(2)
Stream s = new MemoryStream();

XmlWriter xw = new XmlTextWriter( s, Encoding.UTF8 );

xmlSerializer.Serialize( xw, request );

TextReader tr = new StreamReader( s );

s.Seek( 0, SeekOrigin.Begin );

ChargeRequestFactory factory = new ChargeRequestFactory( tr );

In ChargeRequest function I have Deserialize to get XML Back to Object.