将混合的元素数组从XML映射到模型

时间:2017-03-30 13:53:09

标签: c# xml xml-serialization

我有一个XML元素,其中包含两种混合的子元素类型的列表。这使我无法直接使用列表。

例如,我们说我有这样的XML:

<country>
    <city>...</city>
    <village>...</village>
    <village>...</village>
    <city>...</city>
    <village>...</village>
</country>

而不是:

<country>
    <cities>
        <city>...</city>
        <city>...</city>
    </cities>
    <villages>
        <village>...</village>
        <village>...</village>
        <village>...</village>
    </villages>
</country>

我想把它映射到这个模型:

public class Country
{
    public List<string> Cities { get; set; }
    public List<string> Villages { get; set; }
}

第二个例子可以很容易,但我怎么做第一个呢?

1 个答案:

答案 0 :(得分:1)

如果不手动实施IXmlSerializable,我认为你无法做到。如果您必须将XML保留在该表单中,那么模型需要看起来像这样:

[XmlRoot("country")]
public class Country
{
    [XmlElement("city", typeof(City))]
    [XmlElement("village", typeof(Village))]
    public List<object> CitiesAndVillages { get; set; }    
}

public class City
{
    [XmlText]
    public string Value { get; set; }
}

public class Village
{
    [XmlText]
    public string Value { get; set; }
}

有关演示,请参阅this fiddle。请注意,您也可以使用带有关联choice identifier的单个List<string>,但我通常更喜欢这种方法。

此类问题的另一个提示是将XML复制到剪贴板并在Visual Studio中使用Edit |> Paste Special |> Paste XML As Classes。这神奇地生成了一些将反序列化给定XML的类。

相关问题