Search code examples
c#xmlasp.net-coresoapxml-deserialization

ASP.NET Core - Deserialize Cities API XML response not working


When calling cities API, it returns this response in XML format. I want to deserialize this XML into an object. Deserialization grabs objects till diffgram inside diffgram we have the NewDataSet property which returns null and I need to get Cities.

API response:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <soap:Body>
          <getRTLCitiesResponse xmlns="http://track.smsaexpress.com/secom/">
             <getRTLCitiesResult>
                <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">
                   <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
                      <xs:complexType>
                         <xs:choice minOccurs="0" maxOccurs="unbounded">
                            <xs:element name="RetailCities">
                               <xs:complexType>
                                  <xs:sequence>
                                     <xs:element name="routCode" type="xs:string" minOccurs="0" />
                                     <xs:element name="rCity" type="xs:string" minOccurs="0" />
                                  </xs:sequence>
                               </xs:complexType>
                            </xs:element>
                         </xs:choice>
                      </xs:complexType>
                   </xs:element>
                </xs:schema>
                <diffgr:diffgram xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
                   <NewDataSet xmlns="">
                      <RetailCities diffgr:id="RetailCities1" msdata:rowOrder="0">
                         <routCode>ABT</routCode>
                         <rCity>Aqiq</rCity>
                      </RetailCities>
                      <RetailCities diffgr:id="RetailCities2" msdata:rowOrder="1">
                         <routCode>ABT</routCode>
                         <rCity>Atawlah</rCity>
                      </RetailCities>
                      <RetailCities diffgr:id="RetailCities3" msdata:rowOrder="2">
                         <routCode>ABT</routCode>
                         <rCity>Baha</rCity>
                      </RetailCities>
                   </NewDataSet>
                </diffgr:diffgram>
             </getRTLCitiesResult>
          </getRTLCitiesResponse>
       </soap:Body>
</soap:Envelope>

Code details:

 [XmlRoot(ElementName = "RetailCities")]
 public class RetailCity
 {
     [XmlElement(ElementName = "routCode")]
     public string RoutCode { get; set; }

     [XmlElement(ElementName = "rCity")]
     public string RCity { get; set; }
 }

 [XmlRoot(ElementName = "NewDataSet")]
 public class NewDataSet
 {
     [XmlElement(ElementName = "RetailCities")]
     public List<RetailCity> RetailCities { get; set; } = new List<RetailCity>();
 }

 [XmlRoot(ElementName = "diffgram", Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1")]
 public class Diffgram
 {
     [XmlElement(ElementName = "NewDataSet")]
     public NewDataSet NewDataSet { get; set; }
 }

 [XmlRoot(ElementName = "getRTLCitiesResult", Namespace = "http://track.smsaexpress.com/secom/")]
 public class GetRTLCitiesResult
 {
     [XmlElement(ElementName = "diffgram", Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1")]
     public Diffgram Diffgram { get; set; }
 }

 [XmlRoot(ElementName = "getRTLCitiesResponse", Namespace = "http://track.smsaexpress.com/secom/")]
 public class GetRTLCitiesResponse
 {
     [XmlElement(ElementName = "getRTLCitiesResult")]
     public GetRTLCitiesResult GetRTLCitiesResult { get; set; }
 }

 [XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
 public class SoapBody
 {
     [XmlElement(ElementName = "getRTLCitiesResponse", Namespace = "http://track.smsaexpress.com/secom/")]
     public GetRTLCitiesResponse GetRTLCitiesResponse { get; set; }
 }

 [XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
 public class SoapEnvelope
 {
     [XmlElement(ElementName = "Body")]
     public SoapBody Body { get; set; }

     [XmlNamespaceDeclarations]
     public XmlSerializerNamespaces Xmlns { get; set; } = new XmlSerializerNamespaces();

     public SoapEnvelope()
     {
         Xmlns.Add("soap", "http://schemas.xmlsoap.org/soap/envelope/");
         Xmlns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
         Xmlns.Add("xsd", "http://www.w3.org/2001/XMLSchema");
     }
 }


  private static T DeserializeXml<T>(string xml)
  {
      XmlSerializer serializer = new XmlSerializer(typeof(T));
      using (StringReader reader = new StringReader(xml))
      {
          return (T)serializer.Deserialize(reader)!;
      }
  }

Calling API and deserializing XML response:

using (var client = new HttpClient())
{
    var content = new StringContent(AramexCitiesSoapEnvelope(), Encoding.UTF8, "text/xml");

    try
    {
        var response = await client.PostAsync(endPoint, content);

        if (response.IsSuccessStatusCode)
        {
            // Read and return the response content
            var resultContent = await response.Content.ReadAsStringAsync();                 
            var envelope = DeserializeXml<SoapEnvelope>(resultContent);

            return envelope;
        }
        else
        {
            // Return the failed response content
            var errorContent = await response.Content.ReadAsStringAsync();
            return new SoapEnvelope() { ErrorMessage = errorContent };
        }
    }
    catch (HttpRequestException e)
    {
        return new SoapEnvelope() { ErrorMessage = e.Message };
    }
}

Output:

THIS IS SCREENSHOT OF OUTPUT

I have created model classes and decorated these models with XmlElement annotations to deserialize the XML response to get city names located inside the RetailCities list. Still, unfortunately, I'm unable to reach the RetailCities as NewDataSet returns null.


Solution

  • From your XML <NewDataSet xmlns="">, you should add the Namespace = "" in the XmlElement attribute for the NewDataSet property in the Diffgram class.

    [XmlRoot(ElementName = "diffgram", Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1")]
    public class Diffgram
    {
        [XmlElement(ElementName = "NewDataSet", Namespace = "")]
        public NewDataSet NewDataSet { get; set; }
    }