Reputation: 11
I am getting error with deserialization. It says error in xml document.
public T XmlDeserialiseResponseObject<T>(string xml)
{
T returnedXmlClass;
try
{
xml = XmlResponseObjectCleaner(xml);
var doc = new XmlDocument();
doc.LoadXml(xml);
var reader = new XmlNodeReader(doc.DocumentElement);
var ser = new XmlSerializer(typeof(T));
returnedXmlClass = (T)ser.Deserialize(reader);
}
catch (Exception ex)
{
throw ex;
}
return returnedXmlClass;
}
My XML :
<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/elope/'><soap:Body><GetBenefitStatusFault xmlns:ns2='http://schemas.somesite.co.za/somesite/some/' schemaVersion='1.0'>
<ErrorCode>3513</ErrorCode>
<ErrorMessage>Membership details not valid: Match on initial not found</ErrorMessage>
</GetBenefitStatusFault></soap:Body></soap:Envelope>
XmlResponseObjectCleaner:
private string XmlResponseObjectCleaner(string xml)
{
var sb = new StringBuilder();
sb.Append(xml);
sb.Replace(@"""", "'");
sb.Replace("<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>", "");
sb.Replace("</env:Envelope>", "");
sb.Replace("<env:Header/>", "");
sb.Replace("<env:Body>", "");
sb.Replace("ns3:", "");
sb.Replace("ns2:", "");
sb.Replace("</env:Body>", "");
sb.Replace("env", "");
sb.Replace("T00:00:00.000+02:00", "");
sb.Replace("T00:00:00.000Z", "");
return sb.ToString();
}
Upvotes: 1
Views: 54
Reputation: 1064204
You could:
Here's an approach for 2:
using System.IO; using System.Xml.Serialization; static class P { static void Main() { const string xml = @"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/elope/'><soap:Body><GetBenefitStatusFault xmlns:ns2='http://schemas.somesite.co.za/somesite/some/' schemaVersion='1.0'> <ErrorCode>3513</ErrorCode> <ErrorMessage>Membership details not valid: Match on initial not found</ErrorMessage> </GetBenefitStatusFault></soap:Body></soap:Envelope>"; var obj = XmlDeserialiseResponseObject<GetBenefitBody>(xml); if (obj.GetBenefitStatusFault is Fault f) { System.Console.WriteLine(f.ErrorCode); System.Console.WriteLine(f.ErrorMessage); } } public static T XmlDeserialiseResponseObject<T>(string xml) { var ser = new XmlSerializer(typeof(Envelope<T>)); var obj = (Envelope<T>)ser.Deserialize(new StringReader(xml)); return obj.Body; } } [XmlRoot("Envelope", Namespace = "http://schemas.xmlsoap.org/soap/elope/")] public class Envelope<T> { public T Body { get; set; } } public class GetBenefitBody { [XmlElement(Namespace = "")] public Fault GetBenefitStatusFault { get; set; } } public class Fault { public int ErrorCode { get; set; } public string ErrorMessage { get; set; } }
Upvotes: 1