Friday, May 21, 2010

Using XSD to generate classes

Its really nice to work with classes rather than parsing the XML structure using Xpath or the old fashioned XML reader. You can use XSD.exe to generate a c# class based on the XML document or XML schema and then use it to output an XML file.
1. Open VS command prompt.
2. CD to the location where your XSD file is.
3. Type in XSD -c -l:c# -n:[your namespace] [XSD filename]
This will generate a c# class. You can use that class along with the following code to output an XML file

XmlSerializer xmlSerializer = new XmlSerializer(typeof([Your Class]));
using (XmlWriter writer = XmlWriter.Create("[Path]"))
{
 xmlSerializer.Serialize(writer, [instance of your class]);
writer.Close(); }

No comments:

Post a Comment