gpt4 book ai didi

c# - 如何在不包装元素的情况下对多态数组进行 XML 序列化

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

想要将我的数据序列化为:

<?xml version="1.0" encoding="ibm850"?>
<Batch Name="Test batch">
<ExecuteCommand Command="..." />
<WaitCommand Seconds="5" />
</Batch>

但我得到的是这个(注意包装的 Commands 元素)

<?xml version="1.0" encoding="ibm850"?>
<Batch Name="Test batch">
<Commands><!-- I want to get rid of thiw wrapper Commands element and just -->
<ExecuteCommand Command="..." />
<WaitCommand Seconds="5" />
</Commands>
</Batch>

这是用于生成此代码的示例代码:

public class BaseCommand //base class
{
[XmlAttribute]
public string Result { get; set; }
}

public class ExecuteCommand : BaseCommand
{
[XmlAttribute]
public string Command { get; set; }
}

public class WaitCommand : BaseCommand
{
[XmlAttribute]
public int Seconds { get; set; }
}

public class Batch
{
[XmlAttribute]
public string Name { get; set; }

private List<BaseCommand> _commands = new List<BaseCommand>();
[XmlArrayItem(typeof(ExecuteCommand))]
[XmlArrayItem(typeof(WaitCommand))]
public List<BaseCommand> Commands
{
get
{
return _commands;
}
set
{
_commands = value;
}
}

public static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(Batch));

Batch b = new Batch();
b.Name = "Test batch";
b.Commands.Add(new ExecuteCommand() { Command = "..." });
b.Commands.Add(new WaitCommand() { Seconds = 5 });

serializer.Serialize(Console.Out, b);
Console.Read();
}
}

我搜索并阅读了大量有关该主题的文章。它们似乎都提供了使用单一类类型(不使用继承)序列化集合的解决方案。我使用继承,但似乎没有任何效果。不幸的是,由于遗留支持,我必须输出精确的 XML 文档

最佳答案

这是很久以前的事了,但我最终自己弄明白了。

解决方案是为每个支持的派生类型添加 [XmlElement] 属性到集合属性

private List<BaseCommand> _commands = new List<BaseCommand>();
[XmlElement(typeof(ExecuteCommand))]
[XmlElement(typeof(WaitCommand))]
public List<BaseCommand> Commands
{
get
{
return _commands;
}
set
{
_commands = value;
}
}

关于c# - 如何在不包装元素的情况下对多态数组进行 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11572981/

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