如何反序化:
<c:replyMessage
xmlns:c="urn:schemas-cybersource-com:transaction-data-1.118">
<c:merchantReferenceCode>cmAction12345</c:merchantReferenceCode>
<c:requestID>3473543574375349573452</c:requestID>
<c:caseManagementActionReply>
<c:reasonCode>100</c:reasonCode>
</c:caseManagementActionReply>
</c:replyMessage>
我在fiddler响应中收到此错误:
<replyMessage xmlns='urn:schemas-cybersource-com:transaction-data-1.118'> was not expected.
我在mvc action上使用了接受xml的binder:
public class XmlModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
var contentType = System.Web.HttpContext.Current.Request.ContentType;
if (string.Compare(contentType, @"text/xml",
StringComparison.OrdinalIgnoreCase) != 0)
{
return null;
}
return new XmlModelBinder();
}
}
public class XmlModelBinder : IModelBinder
{
public object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var modelType = bindingContext.ModelType;
var serializer = new XmlSerializer(modelType);
var inputStream = controllerContext.HttpContext.Request.InputStream;
return serializer.Deserialize(inputStream);
}
}
型号:
[XmlRoot("c:caseManagementActionReply")]
public class CCaseManagementActionReply
{
public string ReasonCode { get; set; }
}
[XmlRoot("c:replyMessage")]
public class CReplyMessage
{
[XmlElement(ElementName = "c:merchantReferenceCode")]
public string MerchantReferenceCode { get; set; }
[XmlElement(ElementName = "c:requestID")]
public string RequestID { get; set; }
[XmlElement(ElementName = "c:caseManagementActionReply")]
public CCaseManagementActionReply CaseManagementActionReply { get; set; }
}
答案 0 :(得分:2)
您为不同的属性使用相同的元素名称。我认为只是一个复制/粘贴错误:
[XmlElement(ElementName = "c:merchantReferenceCode")]
public string MerchantReferenceCode { get; set; }
[XmlElement(ElementName = "c:merchantReferenceCode")]
public string Decision { get; set; }
<强>更新强>
您应该在XmlRoot属性中指定命名空间。我测试了下面的类,它成功地序列化了样本XML:
[XmlRoot("replyMessage", Namespace= "urn:schemas-cybersource-com:transaction-data-1.118")]
public class CReplyMessage
{
[XmlElement(ElementName = "merchantReferenceCode")]
public string MerchantReferenceCode { get; set; }
[XmlElement(ElementName = "requestID")]
public string RequestID { get; set; }
[XmlElement(ElementName = "caseManagementActionReply")]
public CCaseManagementActionReply CaseManagementActionReply { get; set; }
}
public class CCaseManagementActionReply
{
[XmlElement(ElementName = "reasonCode")]
public string ReasonCode { get; set; }
}