【问题标题】:How to deseriealize XML items as different objects?如何将 XML 项反序列化为不同的对象?
【发布时间】: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 类,它是 PageGhost 的基类,但我不确定如何让反序列化器处理这个问题。

【问题讨论】:

  • 反序列化器将看到元素名称并实例化适当的具体类,Page 或 Ghost。 Items 虽然应该是 List&lt;BasePage&gt;

标签: c# xml-deserialization


【解决方案1】:
[XmlRoot("ColorPages")]
public class ColorPages
{
    [XmlElement("Ghost")]
    List<Ghost> ghost{ get; set; }

    [XmlElement("Page")]
    List<Page> page{ get; set; }
}
[XmlRoot("Ghost")]
public class Ghost
{

}
[XmlRoot("Page")]
public class Page
{

}

【讨论】:

  • 谢谢,太好了!
猜你喜欢
  • 2017-08-20
  • 2018-10-11
  • 2020-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
相关资源
最近更新 更多