How to serialize a class generated from XSD to XML

I created an XSD file from Visual Studio and can also generate an XML sample, but my goal is to use this XSD to create an XML file at runtime.

I used XSD.exe to create a class from my XSD file, and then created a program to populate the object from the "class". How can I serialize an object in an XML file?

+4
source share
3 answers

When you created classes for serializing and deserializing the Xml file using the XSD.exe tool, you can write your instances back to the files using.

Serialization ! ( Archive )

Stream stream = File.Open(filename, FileMode.Create); XmlFormatter formatter = new XmlFormatter (typeof(XmlObjectToSerialize)); formatter.Serialize(stream, xmlObjectToSerialize); stream.Flush(); 
+3
source

Both of these examples leave the stream open, and the XmlFormatter is part of the BizTalk libraries - so the XmlSerializer would be more appropriate:

 using (Stream stream = File.Open(fileName, FileMode.Create)) { XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); serializer.Serialize(stream, MyObject); stream.Flush(); } 
+7
source

The binary format is binary, use the XML version for XML:

 XmlFormatter serializer = new XmlFormatter(typeof(MyObject)); serializer.Serialize(stream, object1); 
0
source

All Articles