SyntaxHighlighter

Saturday, 20 November 2010

Content Pipeline extensions

Well I've had some fun so far today. I finally got tired of my firewall sandboxing my application every time I needed to use XmlSerializer to load a map file, meaning that I needed to recompile twice everytime I made a change to the source code.

So I decided to try and use the Content pipeline to load my maps. This would also have the advantage of compiling my maps to the binary xnb format, taking advantage of the format's compression.

It took me a while to get my head around it, but eventually I came up with the following importer:



[ContentImporter(".mm", DefaultProcessor = "", DisplayName = "AETileMapImporter")]
public class AETileMapImporter : XmlImporter
{
      public AETileMapImporter()
           : base()
       {
       }

       public override object Import(string filename, ContentImporterContext context)
       {

           SaveMapStruct retMapStruct = new SaveMapStruct();

           FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);
           try
           {
               XmlSerializer serializer = new XmlSerializer(typeof(SaveMapStruct));
               retMapStruct = (SaveMapStruct)serializer.Deserialize(stream);

           }
           finally
           {
               stream.Close();
           }

           XmlWriterSettings settings = new XmlWriterSettings();
           settings.Indent = true;
           filename += "X";
           using (XmlWriter writer = XmlWriter.Create(filename, settings))
           {
               IntermediateSerializer.Serialize(writer, retMapStruct, null);
           }

           return base.Import(filename, context);
       }

}



This code could easily be tweaked by others to use for their own custom importer, allowing them to import xml files serialized with XmlSerializer.

Hope someone finds it useful!

No comments:

Post a Comment