简体   繁体   中英

Map mixed arrays of elements from XML to a model

I have an XML element that has lists of 2 types of child elements that are mixed. This precludes me from using lists directly.

For example, let's say I have XML like this:

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

Instead of this:

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

And I want to map it to this model:

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

This would be easy with the second example but how do I do it for the first?

I don't think you can without implementing IXmlSerializable manually. If you have to keep the XML in that form, then the model would need to look something like this:

[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; }
}

See this fiddle for a demo. Note you could also use a single List<string> with an associated choice identifier , but II usually prefer this sort of approach.

One further tip for this sort of problem is to copy your XML to the clipboard and use Edit |> Paste Special |> Paste XML As Classes in Visual Studio. This magically generates some classes that will deserialise the given XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM