Monday, June 8, 2009

using an XSD.exe generated class

When you have an XSD you can use XSD.EXE to generate a class. This can then be used so that you modify properties that will be mapped and serialized to XML nodes as defined by the XSD.

Some concerns though:
- The cs file generated from the XSD through XSD.EXE would by default use an array for anything with multiple cardinality. This is a major pain, so i'd change that to
List <MultipleStuffType >
.
- You must also add a default empty parameterless constructor to your generated type as the XML serialization might not work otherwise.
- Finally, XmlTypeAttribute(AnonymousType=true) to false on a class that is defined as true by default.

Once that is done, you can nicely poke around on your class instance and when you feel fit, serialize:

static XmlSerializer _serializer = new XmlSerializer(typeof(RootElementType), new Type[] { typeof(RootElementType), typeof(List < MultipleStuffType > ), typeof(MultipleStuffType) });

using (TextWriter writer_ = new StreamWriter(targetFile))
{
_serializer.Serialize(writer_, xmlClassInstanceYouWorkedWith);
writer_.Flush();
writer_.Close();
}


and vica versa:

RootElementType stuff_ = (RootElementType)_serializer.Deserialize(XmlReader.Create(targetFile));

No comments:

Post a Comment