namespace testapp { using System.IO; using System.Xml.Serialization; public class Program { public string Time; public string Source; public static void Main() { var data = new Program { Time = "abc", Source = "buffalo", }; var serializer = new XmlSerializer(typeof(Program)); using (var stream = new StreamWriter("E:\cap_test.xml")) { serializer.Serialize(stream, data); } } } }
我的架构:
和我的xml文件:
abc buffalo
您应该使用从xsd生成的类,而不是使用Program 。 当我跑
xsd /classes schema.xsd
它创建一个schema.cs文件。 当我在我的项目中包含它时,我可以编写这段代码:
class Program { public static void Main() { var data = new capType { tel = new[] { new telType { source = "buffalo", time = 1 } } }; var serializer = new XmlSerializer(typeof(capType)); using (var stream = new StreamWriter(@"E:cap_test.xml")) { serializer.Serialize(stream, data); } } }