将xml响应映射到类?

我不知道如何将一些XML表示为C#类。 有没有人有任何关于如何正确映射这个xml的建议? 以下是我的尝试:

  1 5   public class authenticationResponse { [XmlElement("Accounts")] [DataMember] public List Accounts { get; set; } } public class Account { public long id { get; set; } } 

您可以通过LINQ to XML加载此数据:

 XElement x = XElement.Load("YourFile.xml"); List accounts = x.Element("Accounts") .Elements("AccountId") .Select(e => new Account { id = (long)e }) .ToList(); 

在这种情况下, authenticationResponse类是多余的。

如果您在内存中有响应(不在硬盘上的文件中),您可以使用:

 string response = ... XElement x = XElement.Load(new StringReader(response)); 

Visual Studio 2012具有这个很酷的function,称为“将XML粘贴为类”(在“编辑”>“选择性粘贴”下)。 您只需将XML复制到剪贴板中,这个“粘贴XML作为类”function将为您生成并粘贴此authenticationResponse类:

 ///  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public partial class authenticationResponse { private byte[] accountsField; ///  [System.Xml.Serialization.XmlArrayAttribute()] [System.Xml.Serialization.XmlArrayItemAttribute("AccountId", IsNullable = false)] public byte[] Accounts { get { return this.accountsField; } set { this.accountsField = value; } } } 

您可以将XML反序列化为以下类:

 [XmlRoot("authenticationResponse")] public class AuthenticationResponse { [XmlArrayItem("AccountId")] public List Accounts { get; set; } } 

以下是反序列化的代码:

 AuthenticationResponse response = null; var serializer = new XmlSerializer(typeof(AuthenticationResponse)); using (StringReader sr = new StringReader(xml)) { response = (AuthenticationResponse)serializer.Deserialize(sr); } 

我不使用Visual Studio 2012,因此不要将Paste XML作为Class。 但是,在这种情况下,如果我需要快速解决方案,我经常使用Visual Studio工具中的xsd.exe程序。 它从XML模式定义(.xsd文件)生成C#类。

如果您没有针对相关XML的XSD,则可以从许多XML工具中快速生成一个XSD。 我使用oXygen(可以使用试用版),加载XML示例,然后选择Tools | 生成/转换架构。 从长远来看,假设您不想依赖第三方工具,我坚持认为XML数据的来源也为我提供了Schema。

示例xsd.exe命令行(从Visual Studio命令提示符运行):

  xsd.exe FileName.xsd /n:Namespace.Cust.App.UI /c 

将生成一个名为FileName.cs的.cs文件。