1
我使用Visual Studio xsd工具生成了帶有XML模式(.xsd)的類。現在我有了這個類,我想將該對象輸出回由xsd定義的XML。我想知道如何做到這一點。 謝謝!如何使用XmlTextWriter將對象寫入XML?
我使用Visual Studio xsd工具生成了帶有XML模式(.xsd)的類。現在我有了這個類,我想將該對象輸出回由xsd定義的XML。我想知道如何做到這一點。 謝謝!如何使用XmlTextWriter將對象寫入XML?
你需要一個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);
}
太謝謝你了! – formatjam