带有C#信封的对象的XML序列化

Tho*_*mar 7 c# xml serialization xml-serialization

我需要在C#中将对象序列化为XML.物体应包裹在信封中.为此,我创建了以下Envelope类:

[XmlInclude(typeof(Person))]
public class Envelope
{
    public string SomeValue { get; set; }
    public object WrappedObject { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我使用以下代码序列化类:

string fileName = ...;
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
TextWriter textWriter = new StreamWriter(fileName);
try
{
    serializer.Serialize(textWriter, <instance of envelope>);
}
finally
{
    textWriter.Close();
}
Run Code Online (Sandbox Code Playgroud)

当我将类型的对象分配PersonWrappedObject,我得到以下XML:

<Envelope>
    <SomeValue>...</SomeValue>
    <WrappedObject xsi:type="Person">
        ....
    </WrappedObject>
</Envelope>
Run Code Online (Sandbox Code Playgroud)

问题是,我希望包装对象的标签以我传入的实际类命名.例如,如果我分配了一个Personto 的实例WrappedObject,我希望XML看起来如下所示:

<Envelope>
    <SomeValue>...</SomeValue>
    <Person>
        ....
    </Person>
</Envelope>
Run Code Online (Sandbox Code Playgroud)

如果我指定一个实例Animal,我想得到

<Envelope>
    <SomeValue>...</SomeValue>
    <Animal>
        ....
    </Animal>
</Envelope>
Run Code Online (Sandbox Code Playgroud)

我怎么做到这一点?

编辑

实际上我已经简化了我的例子......被包裹的对象实际上又被包裹了:

public class Envelope
{
    public string SomeValue { get; set; }
    public Wrapper Wrap { get; set; }
}

[XmlInclude(typeof(Person))]
public class Wrapper
{
    public object WrappedObject { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我如何使用属性覆盖来处理这个?

Ali*_*tad 6

您需要使用属性覆盖.我正在大量使用它,因为我做了很多自定义序列化.

这是一个粗略的未经测试的片段,但应指向正确的方向:

XmlAttributes attributes = new XmlAttributes();
XmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides();
attributes.XmlElements.Add(new XmlElementAttribute("Person", t));
xmlAttributeOverrides.Add(typeof(Person), "WrappedObject", attributes);
XmlSerializer myserialiser = new XmlSerializer(typeof(Envelope), xmlAttributeOverrides);
Run Code Online (Sandbox Code Playgroud)