开发者

How create a serializable C# class from XML file

开发者 https://www.devze.com 2023-01-28 11:23 出处:网络
I am fairly new to XML 开发者_如何学JAVAin .net.As part of mytaski 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 XMLsimil

I am fairly new to XML 开发者_如何学JAVAin .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!!


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消