简体   繁体   English

XML序列化-多种类型的集合

[英]XML serialization - collection of multiple types

I want to put inside Submenu two different tags: Item and Separator and then parse XML document with XmlSerializer. 我想在子Submenu放入两个不同的标签: ItemSeparator ,然后使用XmlSerializer解析XML文档。 I can do it when Submenu contains only Item sequence. 当子Submenu仅包含Item序列时,我可以这样做。

Exemplary XML document: 示例XML文档:

<?xml version="1.0" encoding="utf-8" ?>
<Navigation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="...">
  <Menu Name="Main">
    <Item Caption="File">
      <Submenu>
        <Item Caption="New" Command="." />
        <Item Caption="Open" Command="." />
        <Separator />
        <Item Caption="Exit" Command="." />
      </Submenu>
    </Item>
  </Menu>
</Navigation>

And (not) working C# code: 和(不)有效的C#代码:

[Serializable]
[XmlRoot("Navigation", IsNullable = false)]
public class Navigation
{
    [XmlElement("Menu")]
    public List<Menu> MenuCollection { get; set; }
}

[Serializable]
[XmlRoot("Menu", IsNullable = false)]
public class Menu
{
    [XmlAttribute("Name")]
    public string Name { get; set; }

    [XmlElement("Item")]
    public List<Item> Items { get; set; }
}

[Serializable]
[XmlRoot("Item", IsNullable = false)]
public class Item
{

    [XmlAttribute("Caption")]
    public string Caption { get; set; }

    [XmlAttribute("Command")]
    public string Command { get; set; }

    [XmlElement("Submenu", IsNullable = true)]
    public Menu Submenu { get; set; }
}

Menu.Items should contains Items and Separators. Menu.Items应包含项目和分隔符。 How can I do it? 我该怎么做?

Although conceptually a menu item and a separator are two different things, it's easiest to think of them both as menu items. 尽管从概念上讲菜单项和分隔符是两个不同的东西,但最容易将它们都视为菜单项。 Add a new property to your Menu class: 将新属性添加到您的Menu类:

    [XmlAttribute]
    public bool IsSeparator { get; set; }

This way, Menu.Items need only ever contain Items . 这样, Menu.Items仅需要包含Items Your XML will end up with elements such as 您的XML最终将包含诸如

    <Item IsSeparator="true" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM