c# - 我需要知道如何将特定的 XML 反序列化为 C# 中自定义类中定义的对象

标签 c# .net xml serialization xml-serialization

给定以下 XML:

   <?xml version="1.0" encoding="UTF-8"?>
   <userAttributeList>
       <attribute>
          <userId>12345678</userId>
          <attId>1234</attId>
          <attName>Group</attName>
          <attTypeId>8</attTypeId>
          <attTypeName>User Group</attTypeName>
          <attData>Member</attData>
       </attribute>
       <attribute>
          <userId>12345678</userId>
          <attId>1235</attId>
          <attName>Contact Name</attName>
          <attTypeId>16</attTypeId>
          <attTypeName>Contact Center Greeting</attTypeName>
          <attData>John Smith</attData>
      </attribute>
      ...
    </userAttributeList>

我想将它反序列化为以下类:

[Serializable]
[XmlTypeAttribute(AnonymousType = true)]
public class UserAttributeList
{
    [XmlArray(ElementName = "userAttributeList")]
    [XmlArrayItem(ElementName = "attribute")]
    public List<UserAttribute> attributes { get; set; }

    public UserAttributeList()
    {
        attributes = new List<UserAttribute>();
    }
}


[Serializable]
public class UserAttribute
{
    public String userId { get; set; }
    public String attId { get; set; }
    public String attName { get; set; }
    public String attTypeId { get; set; }
    public String attTypeName { get; set; }
    public String attData { get; set; }
}

使用下面的代码,其中 GetResponseStream() 返回上面列出的 XML 对象:

XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "userAttributeList";
xRoot.IsNullable = true;

XmlSerializer serializer = new XmlSerializer(typeof(UserAttributeList), xRoot);

try
{
    return (UserAttributeList)serializer.Deserialize(request.GetResponse().GetResponseStream());
}
catch (Exception exc)
{
    return null;
}

我的代码编译没有错误,但返回的 UserAttributeList 显示没有子“属性”项。没有抛出错误

最佳答案

我宁愿做这样的事情:

public class userAttributeList
{
    [XmlElement]
    public List<UserAttribute> attribute { get; set; }

    public UserAttributeList()
    {
        attribute = new List<UserAttribute>();
    }
}

public class UserAttribute
{
    public int userId { get; set; }
    public int attId { get; set; }
    public string attName { get; set; }
    public int attTypeId { get; set; }
    public string attTypeName { get; set; }
    public string attData { get; set; }
}

关于c# - 我需要知道如何将特定的 XML 反序列化为 C# 中自定义类中定义的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4328750/

相关文章:

c# - 在c#中多次运行RegisterStartupScript

.net - 在WiX中创建EventLog源,而没有事件消息文件

c# - Control.Invoke() 挂起应用程序

javascript - 从 XML 加载游戏图 block 数据并使用 jQuery 渲染新图 block

css - 如何在 XSLT 中获取父节点并将其加粗(应用任何样式)?

c# - Fluent Validation - 当特定验证失败时停止验证所有其他验证

c# - 使用 log4net 写入不同的记录器

c# - Windows 工作流基础。我应该使用它吗?

c# - 如何将WPF英寸单位转换为Winforms像素,反之亦然?

android - 错误-无法加载未知错误的AppCompat Actionbar