Serialize object to XmlDocument

前端 未结 1 617
北荒
北荒 2020-12-08 08:36

In order to return useful information in SoapException.Detail for an asmx web service, I took an idea from WCF and created a fault class to contain said useful

1条回答
  •  一生所求
    2020-12-08 09:05

    EDIT: Creates output inside of detail element

    public class MyFault
    {
        public int ErrorCode { get; set; }
        public string ErrorMessage { get; set; }
    }
    
    public static XmlDocument SerializeFault()
    {
        var fault = new MyFault
                        {
                            ErrorCode = 1,
                            ErrorMessage = "This is an error"
                        };
    
        var faultDocument = new XmlDocument();
        var nav = faultDocument.CreateNavigator();
        using (var writer = nav.AppendChild())
        {
            var ser = new XmlSerializer(fault.GetType());
            ser.Serialize(writer, fault);
        }
    
        var detailDocument = new XmlDocument();
        var detailElement = detailDocument.CreateElement(
            "exc", 
            SoapException.DetailElementName.Name,
            SoapException.DetailElementName.Namespace);
        detailDocument.AppendChild(detailElement);
        detailElement.AppendChild(
            detailDocument.ImportNode(
                faultDocument.DocumentElement, true));
        return detailDocument;
    }
    

    0 讨论(0)
提交回复
热议问题