8/08/2005

XMLFragmentWriter

Scott Hanselman blogs about a GotDotNet user sample that allows you to strip document declaration

http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=fcaee1b2-79c2-4b60-ab6b-3a0a9e13bbe3


However, one of the comments to the posted solution comes up with what may be an even more elegant solution that does not rely on reflection:

"Rather than use reflection and change the internal state of the writer, you could also write something to the XmlTextWriter instance. "

Here is s "short but complete" (a la Jon Skeet) example I whipped up:

using System;
using System.Xml;
using System.Xml.Serialization ;
using System.IO;
namespace XmlserializerFaker
{
public class SerializationHelper
{
public static string ToXml( Object o )
{
XmlSerializer serializer =
new XmlSerializer( o.GetType() );
StringWriter stringWriter =
new StringWriter();
// Create an instance of an xml text writer, with no formatting.
// Then write something (actually nothing) to the writer
// in order to set the internal state to something other than the
// start state, which omits the xml declaration.
XmlTextWriter xmlWriter = new XmlTextWriter( stringWriter );
xmlWriter.Formatting = Formatting.None;
xmlWriter.WriteRaw( "" );
// Faking the existence of custom namespaces has a nice side effect
// of leaving namespaces out entirely.
XmlSerializerNamespaces faker = new XmlSerializerNamespaces();
faker.Add( "",
null );
serializer.Serialize( xmlWriter, o, faker );
return stringWriter.ToString();
}
}
public class EngineState
{
private string _name;
public string Name
{
get{ return _name;}
set{_name=value;}
}
public EngineState(){}
public EngineState(string name)
{

this.Name =name;
}
}
class ShowMe
{
[STAThread]
static void Main(string[] args)
{
EngineState st =
new EngineState("Ted");
string x= SerializationHelper.ToXml(st);
Console.WriteLine (x);
Console.ReadLine();
}
}
}


This kind of trick can be especially useful to serialize a class that represents a state or configuration, and just save it as more or less a "config" file.