C# 如何将属性为另一种复杂对象类型的对象序列化为XML/SOAP?我不断得到无效的文档结构

C# 如何将属性为另一种复杂对象类型的对象序列化为XML/SOAP?我不断得到无效的文档结构,c#,xml,soap,C#,Xml,Soap,我试图将一组非常简单的C代码序列化为XML/SOAP。我试图序列化的类类型有一个属性,它是另一个类类型。我不断收到一个错误,该文档在Epilog中失败,并将创建一个无效的XML文档。准确的错误信息如下 状态Epilog中的令牌StartElement将导致无效的XML 文件 下面是我的测试代码集 using System; using System.IO; using System.Xml.Serialization; public class Prog

我试图将一组非常简单的C代码序列化为XML/SOAP。我试图序列化的类类型有一个属性,它是另一个类类型。我不断收到一个错误,该文档在Epilog中失败,并将创建一个无效的XML文档。准确的错误信息如下

状态Epilog中的令牌StartElement将导致无效的XML 文件

下面是我的测试代码集

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; }
    }
}
这是我指向.net fiddle页面的链接:

如何使此文件序列化?

为什么要使用:

var mapping = new SoapReflectionImporter().ImportTypeMapping(typeof(Envelope));
有没有具体的原因?如果跳过该部分并将卵泡线更改为:

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

它序列化了类。

之所以使用它,是因为我在其他地方看到过它。不过,您的代码是有效的。谢谢