Reputation: 148
I have a soap result in this format
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<sendSmsResponse xmlns="https://srvc.blablabla.com/SmsProxy">
<sendSmsResult>
<ErrorCode>0</ErrorCode>
<PacketId>90279163</PacketId>
<MessageIdList>
<MessageId>4402101870</MessageId>
<MessageId>4402101871</MessageId>
</MessageIdList>
</sendSmsResult>
</sendSmsResponse>
</soap:Body>
</soap:Envelope>
I want to convert it to an object in order to use it in my Windows service.
Here is the code for doing that:
public static T DeserializeInnerSoapObject<T>(string soapResponse)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(soapResponse);
var soapBody = xmlDocument.GetElementsByTagName("sendSmsResponse")[0];
string innerObject = soapBody.InnerXml;
XmlSerializer deserializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(innerObject))
{
return (T)deserializer.Deserialize(reader);
}
}
And here are the classes I created for the process:
[XmlRoot(ElementName = "sendSmsResult", Namespace ="https://srvc.blablabla.com/SmsProxy")]
public class sendSmsResult
{
public string ErrorCode { get; set; }
public string PacketId { get; set; }
public MessageId[] MessageIdList{ get; set; }
}
public class MessageId
{
[XmlElement(ElementName = "MessageId", Namespace = "https://srvc.blablabla.com/SmsProxy")]
public string messageId { get; set; }
}
In the service, I call the above method as
var result = DeserializeInnerSoapObject<sendSmsResult>(test);
The result returns correct values for ErrorCode
and PacketId
and the correct number of MessageIds
for MessageIdArray
, but the MessageIds
are null.
Am I doing something wrong with MessageIdArray
?
Any help appreciated.
Upvotes: 0
Views: 359
Reputation: 495
What I like to do when I encounter a problem like this is reverse the process. So create an SendSmsResult object and fill the attributes. Then serialize the object to view the generated xml. This will show you that your code will create an xml looking like this
<?xml version="1.0" encoding="utf-16"?>
<sendSmsResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="https://srvc.blablabla.com/SmsProxy">
<MessageIdList>
<MessageId>
<MessageId>11</MessageId>
</MessageId>
</MessageIdList>
</sendSmsResult>
There is an MessageId element too many.
if you update the class to:
[XmlRoot(ElementName = "sendSmsResult", Namespace = "https://srvc.blablabla.com/SmsProxy")]
public class sendSmsResult
{
public string ErrorCode { get; set; }
public string PacketId { get; set; }
[XmlArrayItem("MessageId", IsNullable = false)]
public List<string> MessageIdList{get;set;}
}
It will work and your properties will be filled with correct data.
Upvotes: 2