How to deserialize xml element attributes in c#

beginer
beginer
68 Points
29 Posts

I'm getting following xml from web response and try to Deserilize it to c# object.

"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n
<PlatformResponse>\r\n
<Errors>\r\n <Error code=\"2005\" message=\"User not found\" />\r\n </Errors>\r\n</PlatformResponse>"

I have following code

StreamReader reader = new StreamReader(webResponse.GetResponseStream());
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Response));
var response = (Response)xmlSerializer.Deserialize(reader);

And the model class

[XmlRoot("PlatformResponse")]
public class Response
{
   [XmlElement("Errors")]
   public Errors Errors { get; set; }
}

public class Errors
{
  [XmlElement("Error")]
  public Error Error { get; set; }
}

public class Error
{
   [XmlAttribute("Code")]
   public string Code { get; set; }
   [XmlAttribute("Message")]
   public string Message { get; set; }
}


I'm not able to Deserialize the Error attribute Code and Message.

Views: 8222
Total Answered: 2
Total Marked As Answer: 0
Posted On: 25-May-2018 00:34

Share:   fb twitter linkedin
what are you getting?
 - Rahul Maurya  25-May-2018 08:40
I'm getting both code and message null
 - beginer  25-May-2018 08:42
Answers
Brian
Brian
Participant
536 Points
73 Posts
     

I think,  attribute name is case sensitive. So can try with small letter as your xml string  showing in small case letter.

public class Error
{
   [XmlAttribute("code")]
   public string Code { get; set; }
   [XmlAttribute("message")]
   public string Message { get; set; }
}

I'm sure it will resolve your problem. thanks

Posted On: 25-May-2018 08:48
Smith
Smith
Participant
360 Points
110 Posts
     

Use following:

StreamReader reader = new StreamReader(webResponse.GetResponseStream());
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Response));
var response = (Response)xmlSerializer.Deserialize(reader);

And the model class

[XmlRoot("PlatformResponse")]
public class Response
{
   [XmlElement("Errors")]
   public Errors Errors { get; set; }
}

public class Errors
{
  [XmlElement("Error")]
  public Error Error { get; set; }
}

public class Error
{
   [XmlAttribute("code")]
   public string Code { get; set; }
   [XmlAttribute("message")]
   public string Message { get; set; }
}
Posted On: 25-May-2018 20:00
banner

Blog

Active User (2)

 Log In to Chat