簡體   English   中英

如何在沒有包裝元素的情況下對多態數組進行XML序列化

[英]How to XML serialize polymorphic array without wrapping element

想要將我的數據序列化為:

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

但相反,我得到這個(注意包裝命令元素)

<?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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM