首先用xsd文件生产对应的C#类,这个VS已经自带此工单,方法如下:
1. 打开交叉命令行工具
2. 输入如下指令
xsd d:\123.xsd /c /language:C# /outputdir:d:\
含义:
将d:\123.xsd 架构 生成类 语言为C# 输出目录是d:\
3. 完成后C#类就在d盘下
然后将C#加载到工程中,可以对其自动生成的类型按需稍作修改;如下介绍一种据此类创建XML的简单Demo:
1 public static string Serialize(Type type, object o) 2 { 3 string result = string.Empty; 4 try 5 { 6 XmlSerializer xs = new XmlSerializer(type); 7 MemoryStream ms = new MemoryStream(); 8 xs.Serialize(ms, o); 9 ms.Seek(0, SeekOrigin.Begin); 10 StreamReader sr = new StreamReader(ms); 11 result = sr.ReadToEnd(); 12 ms.Close(); 13 } 14 catch (Exception ex) 15 { 16 throw ex; 17 } 18 return result; 19 } 20 21 public void CreateXMLByXSD() 22 { 23 XSDClass demo = new XSDClass(); 24 demo.Field1="xx"; 25 ... 26 27 string xmlContent = SerializeHelp.Serialize(typeof(XSDClass), demo); 28 }