How to deserialize xml element attributes in c#

beginer
beginer
1544 Points
52 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: 16328
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
2376 Points
13 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
2890 Points
78 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
 Log In to Chat