Grasshopper
Grasshopper

Reputation: 1808

How create a serializable C# class from XML file

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!!

Upvotes: 5

Views: 18331

Answers (3)

Tim Barrass
Tim Barrass

Reputation: 4939

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.

Upvotes: 4

Greg Sansom
Greg Sansom

Reputation: 20870

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.

Upvotes: 11

Davita
Davita

Reputation: 9144

here's a good example how to serialize/deserialize an object. http://sharpertutorials.com/serialization/

Upvotes: -1

Related Questions