formatjam
formatjam

Reputation: 347

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!

Upvotes: 1

Views: 2750

Answers (1)

Filburt
Filburt

Reputation: 18061

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

Upvotes: 2

Related Questions