2

Given the following 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>

I want to deserialize it into the following classes:

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

Using the code below, where GetResponseStream() returns the XML object listed above:

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

My code compiles with no errors, but the UserAttributeList that is returned shows no child "attribute" items. No errors are thrown

mdonley
  • 43
  • 4

2 Answers2

0

I would sooner do something like:

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; }
}
Reinderien
  • 11,755
  • 5
  • 49
  • 77
  • I knew it would be something simple like that. I guess I was making it too difficult on myself. thanks! – mdonley Dec 01 '10 at 20:42
0

Personally I'd use LinqToXsd. Take the existing xml, generate an xsd from it then use LinqToXsd to load that xml into a LinqToXsd object. Then you can do things like:

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

to build a POCO.

jcollum
  • 43,623
  • 55
  • 191
  • 321