如何使用XmlTextWriter将对象写入XML?

时间:2012-07-01 07:24:06

标签: c# .net xml xsd xmltextwriter

我使用Visual Studio xsd工具生成了一个带有XML Schema(.xsd)的类。现在我有了这个类,我希望将该对象输出回我的xsd定义的XML。我想知道该怎么做。 谢谢!

1 个答案:

答案 0 :(得分:2)

您需要XmlSerializer来处理课程序列化:

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