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

时间:2010-12-01 20:26:36

标签: 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没有显示子“属性”项。没有错误被抛出

2 个答案:

答案 0 :(得分:0)

我会更早做一些事情:

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

答案 1 :(得分:0)

我个人使用LinqToXsd。获取现有的xml,从中生成xsd,然后使用LinqToXsd将该xml加载到LinqToXsd对象中。然后你可以做以下事情:

xml.company.com.reports.report.Load(xmlFileContents); 

建立POCO。

相关问题