1

我有看起来像这样的xml

<root>
    <bosses>
        <boss>..some elements..</boss>
        <boss>..some elements..</boss>
    </bosses>
    <workers>
        <worker>..some elements..not the same as bosses</worker>
        <worker>..some elements..</worker>
    </workers>
</root>

和一些看起来像这样的类

public class Person
{
    //properties common to both bosses and workers
}

public class Boss : Person
{
    //some properties unique for bosses
}

public class Worker : Person
{
    //some properties unique for workers        
}

现在,我想做的是将 xml 反序列化为一个List<Person>,但坦率地说,我很难做到这一点。

我可以通过做得到老板和工人的单独清单

    [XmlElement("bosses")]
    public List<Boss> Bosses { get; set; }

    [XmlElement("workers")]
    public List<Worker> Workers { get; set; }

我已经尝试通过这样做天真地结合它们

    [XmlElement("bosses")]
    [XmlElement("workers")]
    public List<Person> People { get; set; }

但它失败了。如果我不得不猜测,那将是我必须告诉 dezerializer 哪个子类Person与老板一起使用,哪个子类与工人一起使用,但即使是这样,我似乎也无法找到它是如何完成的。

所以,请赐教!

编辑(解决方案):你知道吗,问这个问题引发了一些新的想法,我能够找出解决方案。我会把它贴在这里,以防其他人遇到类似问题:

    [XmlElement(ElementName = "bosses", Type = typeof(Boss))]
    [XmlElement(ElementName = "workers", Type = typeof(Worker))]
    public List<Person> People { get; set; }
4

1 回答 1

1

解决方案:

[XmlElement(ElementName = "bosses", Type = typeof(Boss))]
[XmlElement(ElementName = "workers", Type = typeof(Worker))]
public List<Person> People { get; set; }
于 2013-05-02T19:20:10.800 回答