I am fairly new to XML in .net. As part of my task i need to create the class which can be serialized to XML. I have an sample XML file with all the tags(the class should produce XML similar to the sample XML file ). what would be best approach to create the class from XML file?
Thank you in advance!!
To make a Java object serializable we implement the java. io. Serializable interface. The ObjectOutputStream class contains writeObject() method for serializing an Object.
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
The easiest way to make a class serializable is to mark it with the SerializableAttribute as follows. The following code example shows how an instance of this class can be serialized to a file. MyObject obj = new MyObject(); obj. n1 = 1; obj.
You can use XSD.exe to create a .cs file from .xml. http://msdn.microsoft.com/en-us/library/x6c1kb0s%28VS.71%29.aspx
At the command line:
xsd myFile.xml
xsd myFile.xsd
The first line will generate a schema definition file (xsd), the second file should generate a .cs file. I'm not sure if the syntax is exact, but it should get you started.
Working backwards might help -- create your class first, then serialize and see what you get.
For the simplest classes it's actually quite easy. You can use XmlSerializer to serialize, like:
namespace ConsoleApplication1 { public class MyClass { public string SomeProperty { get; set; } } class Program { static void Main(string[] args) { XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); TextWriter writer = new StreamWriter(@"c:\temp\class.xml"); MyClass firstInstance = new MyClass(); firstInstance.SomeProperty = "foo"; // etc serializer.Serialize(writer, firstInstance); writer.Close(); FileStream reader = new FileStream(@"c:\temp\class.xml", FileMode.Open); MyClass secondInstance = (MyClass)serializer.Deserialize(reader); reader.Close(); } } }
This will write a serialized representation of your class in XML to "c:\temp\class.xml". You could take a look and see what you get. In reverse, you can use serializer.Deserialize to instantiate the class from "c:\temp\class.xml".
You can modify the behaviour of he serialization, and deal with unexpected nodes, etc -- take a look at the XmlSerializer MSDN page for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With