Read typed objects from XML using known XSD

You need to do two steps:

1) Take your XML schema file and run it through the xsd.exe utility (which comes with the Windows SDK – it’s in C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\ or some similar path. This can turn the XSD file into a C# class:

xsd /c yourfile.xsd

This should give you a file yourfile.cs which contains a class representing that XML schema.

2) Now, armed with that C# class, you should be able to just deserializing the XML file into an instance of your new object:

XmlSerializer ser = new XmlSerializer(typeof(foo));

string filename = Path.Combine(FilePath, "SimpleFields.xml");

foo myFoo = ser.Deserialize(new FileStream(filename, FileMode.Open)) as foo;

if (myFoo != null)
{
   // do whatever you want with your "foo"
}

That’s about as simple as it gets! 🙂

Leave a Comment

tech