How to serialize to XML / SOAP an object with property that is another complex object type? I keep getting invalid document structure

梦想与她 提交于 2021-02-11 15:17:54

问题


I'm trying to serialize a pretty simple set of C# code to XML / SOAP. The class type that I'm trying to serialize has a single property which is another class type. I keep getting an error that the document fails in the Epilog and would create an invalid XML document. Exact error message is below ...

Token StartElement in state Epilog would result in an invalid XML document.

Below is my test set of code ...

using System;
using System.IO;
using System.Xml.Serialization;
                    
public class Program
{
    public static void Main()
    {
        var mapping = new SoapReflectionImporter().ImportTypeMapping(typeof(Envelope));
        
        var serializer = new XmlSerializer(mapping);
        
        var envelope = new Envelope
        {
            Body = new Body
            {
                Foo = "Testing"
            }
        };

        using (var destination = new StringWriter())
        {
            serializer.Serialize(destination, envelope);

            var result = destination.ToString();

            Console.WriteLine(result);
        }
    }
    
    public class Envelope
    {
        public Body Body { get; set; }
    }
    
    public class Body
    {
        public string Foo { get; set; }
    }
}

And here is my link to a .net fiddle page: https://dotnetfiddle.net/u0oyUo

How can I make this serialize this?


回答1:


why are you using:

var mapping = new SoapReflectionImporter().ImportTypeMapping(typeof(Envelope));

Is there a specific reason for? If you skip that part and change the folling line to:

var serializer = new XmlSerializer(typeof(Envelope));

It serializes the class.



来源:https://stackoverflow.com/questions/63461431/how-to-serialize-to-xml-soap-an-object-with-property-that-is-another-complex-o

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!