jojo
jojo

Reputation: 13843

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?

Upvotes: 5

Views: 21040

Answers (3)

Jaapjan
Jaapjan

Reputation: 3385

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();

Upvotes: 5

Alan B
Alan B

Reputation: 4288

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();
}

Upvotes: 10

KenF
KenF

Reputation: 624

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

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

Upvotes: 0

Related Questions