用抽象类序列化c# XML
本文关键字:XML 序列化 抽象类 | 更新日期: 2023-09-27 18:16:23
我目前正在尝试将一些命令设置为通信协议序列化的类。我的代码基本如下:
[XmlRoot("Message")]
[Serializable]
public class Message
{
private Command[] _commands;
[XmlAttribute("ver")]
public int Version { get; set; }
[XmlAttribute("msid")]
public Guid Id { get; set; }
[XmlArray("Commands")]
[XmlArrayItem(typeof(HealthCheckCommand))]
[XmlArrayItem(typeof(TestCommand))]
public Command[] Commands
{
get { return _commands; }
set { _commands = value; }
}
}
public enum CommandTypes
{
healthcheck
}
[XmlType(TypeName = "Command")]
public abstract class Command
{
String CommandType { get; set; }
}
public class HealthCheckCommand : Command
{
[XmlAttribute("type")]
public string CommandType
{
get { return "healthcheck"; }
set { throw new NotImplementedException(); }
}
}
public class TestCommand : Command
{
[XmlAttribute("type")]
public string CommandType
{
get { return "test"; }
set { throw new NotImplementedException(); }
}
}
我需要得到的是:
<Message ver="1" msid="00000000-0000-0000-0000-000000000000">
<Commands>
<Command type="healthcheck" />
<Command type="test" />
</Commands>
</Message>
我得到的是:
<Message ver="1" msid="00000000-0000-0000-0000-000000000000">
<Commands>
<HealthCheckCommand type="healthcheck" />
<TestCommand type="test" />
</Commands>
</CTM>
当我尝试用相同的名称覆盖XmlArrayItem名称时,它当然会抛出错误。如果我使用列表,那么它可以工作,但是我在子类型中得到了所有名称空间的东西,这是我不想要的。我可以在事后删除这些名称空间项,但我不想这样做。一定有办法的。
谢谢你的帮助!
编辑:序列化代码:
XmlSerializer serializer = new XmlSerializer(typeof (Message));
using (TextWriter writer = new StreamWriter(@"C:'Xml.txt"))
{
XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
xmlSerializerNamespaces.Add("", "");
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
using (
XmlWriter xmlwriter = XmlWriter.Create(writer, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
serializer.Serialize(xmlwriter, message, xmlSerializerNamespaces);
}
}
}
通过将相关的XmlInclude
属性添加到Message
来包含派生类型:
[XmlInclude(typeof(HealthCheckCommand))]
[XmlInclude(typeof(TestCommand))]
然后为您的Command[]
数组项指定元素名称:
[XmlArrayItem("Command")]
这会创建像这样的XML,这可能与使用List
时相同:
<Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ver="0" msid="00000000-0000-0000-0000-000000000000">
<Commands>
<Command xsi:type="HealthCheckCommand" type="healthcheck" />
<Command xsi:type="TestCommand" type="test" />
</Commands>
</Message>
不幸的是,xsi:type
属性是反序列化工作所必需的(否则序列化程序如何知道使用哪种类型?)不过,这些可以很容易地在事后删除。使用XDocument
解析XML并删除它们,如下所示:
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
doc.Descendants()
.Attributes(xsi + "type")
.Remove();
doc.Descendants()
.Attributes()
.Where(a => a.IsNamespaceDeclaration && a.Value == xsi)
.Remove();