Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a class generated from XSD to XML

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

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

like image 825
jojo Avatar asked May 16 '11 05:05

jojo


2 Answers

Both those examples leave the stream open, and XmlFormatter is part of the BizTalk libs - so 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();
}
like image 101
Alan B Avatar answered Sep 30 '22 13:09

Alan B


When you have created classes to serialize and deserialize the Xml file using the XSD.exe tool you can write your instances back to files using ..

Serialization! (Archive)

  Stream stream = File.Open(filename, FileMode.Create);
  XmlFormatter formatter = new XmlFormatter (typeof(XmlObjectToSerialize));
  formatter.Serialize(stream, xmlObjectToSerialize);
  stream.Flush();
like image 43
Jaapjan Avatar answered Sep 30 '22 14:09

Jaapjan