【发布时间】:2018-01-23 14:25:20
【问题描述】:
我正在从第 3 方接收具有这种格式的 XML:
<?xml version="1.0" encoding="utf-16"?>
<ColorPages version="1">
<Page PrintedPagePosition="0" PDFPagePosition="0" IsColor="True" />
<Ghost PrintedPagePosition="1" PDFPagePosition="1" MayBePrinted="Unprinted" IsColor="False" />
<Page PrintedPagePosition="2" PDFPagePosition="2" IsColor="False" />
<Ghost PrintedPagePosition="3" PDFPagePosition="3" MayBePrinted="Unprinted" IsColor="False" />
<Page PrintedPagePosition="4" PDFPagePosition="4" IsColor="False" />
<Page PrintedPagePosition="5" PDFPagePosition="5" IsColor="True" />
</ColorPages>
如果我忽略 Ghost 项,我可以使用这些类轻松反序列化:
[XmlRoot("ColorPages")]
public class ColorPages
{
public ColorPages() { Items = new List<Page>(); }
[XmlElement("Page")]
public List<Page> Items { get; set; }
}
public class Page
{
[XmlAttribute("PDFPagePosition")]
public string PDFPagePosition { get; set; }
[XmlAttribute("IsColor")]
public string IsColor { get; set; }
}
现在,我知道我必须创建一个 BasePage 类,它是 Page 和 Ghost 的基类,但我不确定如何让反序列化器处理这个问题。
【问题讨论】:
-
反序列化器将看到元素名称并实例化适当的具体类,Page 或 Ghost。
Items虽然应该是List<BasePage>