我想在Submenu
内放两个不同的标记:Item
和Separator
,然后使用XmlSerializer解析XML文档。当Submenu
仅包含Item
序列时,我可以这样做。
示例性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>
并且(不)使用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
应包含项目和分隔符。我该怎么办?
答案 0 :(得分:1)
虽然概念上菜单项和分隔符是两个不同的东西,但最容易将它们视为菜单项。将新属性添加到Menu
类:
[XmlAttribute]
public bool IsSeparator { get; set; }
这样,Menu.Items
只需要包含Items
。您的XML最终将使用
<Item IsSeparator="true" />