Serializing XML response from WebService to object (C #)

I am making a call to a REST web service.

The answer looks something like this:

<?xml version=\"1.0\" encoding=\"utf-8\"?>
<data>
  <status>1</status>
  <message>OK</message>
  <results>
    <result>
      <account>12345</account>
      <to>012345678</to>
      <from>054321</from>
      <message>Testing</message>
      <flash></flash>
      <replace></replace>
      <report></report>
      <concat></concat>
      <id>f8d3eea1cbf6771a4bb02af3fb15253e</id>
    </result>
  </results>
</data>

      

I have a class called "SMSSendingResponse" that looks like this:

public class SMSSendingResponse
{
    public string AccountNumber { get; set; }
    public string Status { get; set; }
    public string Message { get; set; }
    public string ResponseID { get; set; }
    public SMSMessage SMSMessage { get; set; }
}

      

SMSMessage looks like this:

public class SMSMessage
{
    public string To { get; set; }
    public string From { get; set; }
    public string Message { get; set; }
}

      

As you can see, I am ignoring part of the returned element (flash, replace, etc.)

What's the best way for me to convert the returned XML to this object?

I tried to use the XmlSerializer but it threw an error ... I guess because I am not serializing first using the XmlSerializer.

If it was Json, I would use the NewtonSoft.Json library ... Although I suppose I could convert the xml to json and then serialize that path, is there a better way?

+2
c # xml xml-deserialization


a source to share


2 answers


You can use XmlSerializer

just fine as long as you add the appropriate attributes to the fields of your classes. Check them out with some examples . You will no doubt run into errors the first few times you work with it, but stick with it because once you figure it out, it's a great tool.

EDIT:



It's best to find all the available attributes here . Go through the list for everything that starts with Xml and ends with an attribute. You will know all of them.

+2


a source to share


You can use xsd.exe to extract schema from xml file and create corresponding C # class. You can use the generated class to serialize and deserialize xml. If you show the code, we can more easily identify the error.



0


a source to share







All Articles