Question

I generated a Class with a XML Schema (.xsd) using the Visual Studio xsd tool. Now I have the class and I want to output that object back into XML as defined by my xsd. I am wondering how to do that. Thank you!

Was it helpful?

Solution

You need an XmlSerializer to take care of serializing your class:

using System.Text; // needed to specify output file encoding
using System.Xml;
using System.Xml.Serialization; // XmlSerializer lives here

// instance of your generated class
YourClass c = new YourClass();

// wrap XmlTextWriter into a using block because it supports IDisposable
using (XmlTextWriter tw = new XmlTextWriter(@"C:\MyClass.xml", Encoding.UTF8))
{
    // create an XmlSerializer for your class type
    XmlSerializer xs = new XmlSerializer(typeof(YourClass));

    xs.Serialize(tw, c);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top