Search code examples
c#.netxmlxsdxmltextwriter

How to use XmlTextWriter to write a object into XML?


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!


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);
    }