ruskin
ruskin

Reputation: 489

Serialize and deserialize multiple custom objects to XML

I have to serialize multiple custom objects like Customer, Store, etc. Each object has just properties, and objects no relationship with each other. I have to serialize to XML, and deserialize back to custom objects.

How can I do this in C# ?

Upvotes: 0

Views: 672

Answers (3)

Baz1nga
Baz1nga

Reputation: 15579

Generate the xsd as follows:

 "$(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\@InstallationFolder)\bin\xsd.exe" /n:"$(ProjectName).Namespace" "$(ProjectDir)\<YourXML>" 

This should be a 1 times thing since your validation will stay constant.

create a prebuild event in your project for generating the class as follows:

<PreBuildEvent>
  "$(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\@InstallationFolder)\bin\xsd.exe" /n:"$(ProjectName).Namespace" "$(ProjectDir)\<YourXSD>" /c /o:"$(ProjectDir)\<GeneratedClassFolder>"
</PreBuildEvent>

Then you can use the built in .NET XMLSerializer to write your classes to an XML file.

Upvotes: 1

user807566
user807566

Reputation: 2856

You can make an XSD file defining your classes. Then you can use the built in .NET XMLSerializer to write your classes to an XML file. You can use the XSD to validate your inputs during deserialization.

Or you can apply the Serializable attribute for your classes.

Upvotes: 0

Muad&#39;Dib
Muad&#39;Dib

Reputation: 29286

a quick google reveals this article on Switch On The code with examples on how to serialize and deserialize to XML. here is an code example on serializing and deserializing an object.

static public void SerializeToXML<_type>(_type item,string fileName)
{
  XmlSerializer serializer = new XmlSerializer( item.GetType() );
  TextWriter textWriter = new StreamWriter( fileName );
  serializer.Serialize(textWriter, item);
  textWriter.Close();
}

static _type DeserializeFromXML<_type>(string fileName)
{
   XmlSerializer deserializer = new XmlSerializer(typeof(_type));
   TextReader textReader = new StreamReader( fileName );

   _type item = (_type)deserializer.Deserialize(textReader);
   textReader.Close();

   return item;
}

Upvotes: 0

Related Questions