gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:47:57 25 4
gpt4 key购买 nike

我需要在 C# 中将对象序列化为 XML。这些元素应该用信封包裹。为此,我创建了以下 Envelope 类:

[XmlInclude(typeof(Person))]
public class Envelope
{
public string SomeValue { get; set; }
public object WrappedObject { get; set; }
}

我使用下面的代码来序列化这个类:

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

当我将类型为 Person 的对象分配给 WrappedObject 时,我得到以下 XML:

<Envelope>
<SomeValue>...</SomeValue>
<WrappedObject xsi:type="Person">
....
</WrappedObject>
</Envelope>

问题是,我希望包装对象的标签以我传入的实际类命名。例如,如果我将 Person 的实例分配给 WrappedObject ,我希望 XML 如下所示:

<Envelope>
<SomeValue>...</SomeValue>
<Person>
....
</Person>
</Envelope>

如果我分配一个Animal的实例,我想得到

<Envelope>
<SomeValue>...</SomeValue>
<Animal>
....
</Animal>
</Envelope>

我将如何实现?

编辑

实际上我已经稍微简化了我的示例......包装对象实际上再次包装:

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

[XmlInclude(typeof(Person))]
public class Wrapper
{
public object WrappedObject { get; set; }
}

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

最佳答案

您需要使用 attribute override .我正在大量使用它,因为我做了很多自定义序列化。

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

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);

关于c# - C# 中带有信封的对象的 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5895701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com