I hate all the junk that gets added when serializing object to XML, so here is a quick way to do it cleanly.
Here is the dirty way:
public static string Serialize(this object obj) { string XmlString = String.Empty; using (var memStream = new MemoryStream()) { var serializer = new XmlSerializer(obj.GetType(), string.Empty); using (var xmlText = new XmlTextWriter(memStream, Encoding.Default)) { serializer.Serialize(xmlText, obj); } XmlString = Encoding.Default.GetString(memStream.ToArray()); memStream.Close(); } return XmlString; }
The resulting XML looks like this:
<?xml version="1.0" encoding="Windows-1252"?> <ZipContentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <FileName>00107_tokyoatnight_1680x1050.jpg</FileName> <FileSize>281268</FileSize> </ZipContentInfo>
Here is a cleaner way:
public static string Serialize(this object obj) { var ser = new XmlSerializer(obj.GetType()); using (var tw = new StringWriter()) { using (var xw = XmlWriter.Create(tw, new XmlWriterSettings() { OmitXmlDeclaration = true })) { var ns = new XmlSerializerNamespaces(); //Add an empty namespace and empty value ns.Add("", ""); ser.Serialize(xw, obj, ns); return tw.ToString(); } } }
And the resulting XML looks like this:
<ZipContentInfo>
<FileName>00107_tokyoatnight_1680x1050.jpg</FileName>
<FileSize>281268</FileSize>
</ZipContentInfo>
This entry was posted
on Tuesday, February 23rd, 2010 at 8:08 pm and is filed under Programming.
You can follow any responses to this entry through the RSS 2.0 feed.
Both comments and pings are currently closed.
