前言
XmlSerializer类概述
使用XmlSerializer类时的注意事项
使用XmlSerializer类示例
using System.Xml.Serialization; using System.ServiceModel; namespace Service { [ServiceContract,XmlSerializerFormat] public interface IUserInfo { [OperationContract] User[] GetInfo(); } public class User { [XmlAttribute] public int ID { get; set; } [XmlAttribute] public string Name { get; set; } [XmlAttribute] public int Age { get; set; } [XmlAttribute] public string Nationality { get; set; } } }
UserInfo.cs代码如下:
using System.Collections.Generic; namespace Service { public class UserInfo:IUserInfo { public User[] GetInfo() { List<User> Users = new List<User>(); Users.Add(new User { ID = 1, Name = "JACK", Age = 20, Nationality = "CHINA" }); Users.Add(new User { ID = 2, Name = "TOM", Age = 18, Nationality = "JAPAN" }); Users.Add(new User { ID = 3, Name = "SMITH", Age = 22, Nationality = "KOREA" }); Users.Add(new User { ID = 4, Name = "ALENCE", Age = 21, Nationality = "INDIA" }); Users.Add(new User { ID = 5, Name = "JOHN", Age = 22, Nationality = "SINGAPORE" }); return Users.ToArray(); } } }
2. Host:控制台应用程序,服务承载程序。添加对程序集Service的引用,完成以下代码,寄宿服务。Program.cs代码如下:
using System; using Service; using System.ServiceModel; namespace Host { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(UserInfo))) { host.Opened += delegate { Console.WriteLine("服务已经启动,按任意键终止!"); }; host.Open(); Console.Read(); } } } }View Code
App.config代码如下:
<?xml version="1.0"?> <configuration> <system.serviceModel> <services> <service name="Service.UserInfo" behaviorConfiguration="mexBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:1234/UserInfo/"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="Service.IUserInfo" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="mexBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>View Code
我们通过svcutil.exe工具生成客户端代理类和客户端的配置文件
svcutil.exe是一个命令行工具,位于路径C:/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/Bin下,我们可以通过命令行运行该工具生成客户端代理类
3. Client:控制台应用程序,客户端调用程序。将生成的UserInfoClient.cs和App.config复制到Client的工程目录下,完成客户端调用代码。Program.cs的代码如下:
using System; namespace Client { class Program { static void Main(string[] args) { UserInfoClient proxy = new UserInfoClient(); User[] Users = proxy.GetInfo(); Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}", "ID", "Name", "Age", "Nationality"); for (int i = 0; i < Users.Length; i++) { Console.WriteLine("{0,-10}{1,-10}{2,-10}{3,-10}", Users[i].ID.ToString(), Users[i].Name.ToString(), Users[i].Age.ToString(), Users[i].Nationality.ToString()); } Console.Read(); } } }
程序运行结果如下: