想要将我的数据序列化为以下格式:
<?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文档。