基于xsd模式生成xml(使用.NET)

我想根据我的xsd架构(cap.xsd)生成一个xml文件。 我找到了这篇文章,并按照说明操作: 使用XSD文件生成XML文件

  • 我已经在xsd.exe的帮助下创建了这个类,并通过拖放到我的解决方案中插入它
  • 之后,我构建了我的解决方案并创建了xml。 但它不基于xsd架构。
  • xml文件有一个包含字符的元素,但架构说必须有数字(double)

  • 无论如何,我没有看到xsd架构对生成的xml有什么影响? 如果删除架构,则仍会创建xml文件。 并且在此行创建了xml文件:

    var data = new Program {Time =“abc”,Source =“443543253243”,};

..而不是我的架构:

怎么了?


我的课:

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

写道:

     buffalo   

schema.cs time属性为double类型的事实意味着您只能输入有效数字。