Jul 10, 2012

How To Generate C# Object from XML

Found this from my old work note.  Before I forget about it, let me post it here. Maybe someone find it useful.

Auto-generating a C# object from an XML file. This was something I had to do while trying to import a CAT rigged animation from 3DS Max to my Unity project. A FBX file doesn't correctly export IK-ed CAT rig animations unless every single frame is baked.  So I tried to do it through 3DS Max's animation export feature through an XML file.

I took a look at the XML file thinking I should be able to manually write a C# class that can be deserialized from the XML file.  But I was wrong, the XML file was too complicated.  Then I thought there must be an way to auto-generate a C# object from an XML file.

A quick Google search gave me these two useful stackoverflow pages:

After reading above pages, what I needed to do was basically running the following commands in order in a command prompt window

xsd test.xml /classes -> test.xsd
xsd test.xsd /classes -> test.cs

The first line generates an XML schema file from the given xml, and the 2nd line generates a C# class from the schema. Once this test.cs file is generated all I had to do was using C# XML Serializer to load all the data into a C# object.  It looked something like this

XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(test));
FileStream stream = File.Open(@"test.xml", FileMode.Open);
var a= (test)x.Deserialize(stream);

Simple eh?  Yeah I thought so too :) But unfortunately I couldn't get all the key frame info I wanted from the XML file, either.  So I ended up not using this.  Still a good knowledge to have! :D

No comments:

Post a Comment