Teaching a man to fish

Originally posted to Shawn Hargreaves Blog on MSDN, Tuesday, August 12, 2008

Variants of the following question come up somewhat regularly on the XNA forums:

You already have the tools to answer this yourself. Here's how:

Fire up Visual Studio and create a new Console Application project.

Right-click on the References node, and add the Microsoft.Xna.Framework.Content.Pipeline assembly.

Add using declarations for the System.Xml and Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate namespaces.

Add a test class with the same layout as whatever data you want to serialize, but initialized with dummy test values. For instance:

    namespace XmlTest
    {
        class MyTest
        {
            public int elf = 23;
            public string hello = "Hello World";
        }
    }

Add this code to Main:

    MyTest testData = new MyTest();

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;

    using (XmlWriter writer = XmlWriter.Create("test.xml", settings))
    {
        IntermediateSerializer.Serialize(writer, testData, null);
    }

Run the program. Look in the bin\Debug folder, and open the test.xml output file. With the class shown above, this will look like:

    <?xml version="1.0" encoding="utf-8"?>
    <XnaContent>
      <Asset Type="XmlTest.MyTest">
        <elf>23</elf>
        <hello>Hello World</hello>
      </Asset>
    </XnaContent>

Tada! That's how IntermediateSerializer represents this particular class in XML.

Blog index   -   Back to my homepage