Quantum_Kernel
Quantum_Kernel

Reputation: 343

Deserialize XML arrays using C#

If I have an XML such as the following:

<?xml version="1.0" encoding="UTF-8" ?>
<Config>
    <Interface>
        <Theme>Dark</Theme>
        <Mode>Advanced</Mode>
    </Interface>
    <Export>
        <Destination>\\server1.example.com</Destination>
        <Destination>\\server2.example.com</Destination>
        <Destination>\\server3.example.com</Destination>
    </Export>       
</Config>

I can easily deserialize the XML and get element values in the "Interface" section by the following method:

using System;
using System.IO;
using System.Xml.Serialization;

static void Main(string[] args)
    {
        var serializer = new XmlSerializer(typeof(Config));

        using (var stream = new FileStream(@"C:\Temp\Config.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            var config = (Config)serializer.Deserialize(stream);

            Console.WriteLine($"Theme: {config.Interface.Theme}");
            Console.WriteLine($"Mode: {config.Interface.Mode}");
            Console.ReadKey();
        }
    }


[Serializable, XmlRoot("Config")]
public class Config
{
    public Interface Interface { get; set; }
}

public struct Interface
{
    public string Theme { get; set; }
    public string Mode { get; set; }
}

How should I deserialize the array of "Destination" elements in the "Export" section, such that I can loop through an array object to print the values?

i.e.

foreach (destination d in export)
{
Console.WriteLine(destination);
}

Upvotes: 0

Views: 74

Answers (1)

Innat3
Innat3

Reputation: 3576

You need to add the XmlElementtag with the Destination identifier to declaration of your list in order to populate it

[Serializable, XmlRoot("Config")]
public class Config
{
    public Interface Interface { get; set; }

    public Export Export { get; set; }
}

public struct Export
{
    [XmlElement("Destination")]
    public List<string> Destinations { get; set; }
}

Then you can access the values the following way

foreach (string destination in config.Export.Destinations)
{
    Console.WriteLine(destination);
}

You can also create a custom Destination class instead of using a list of strings by adding the XmlText tag

public struct Export
{
    [XmlElement("Destination")]
    public List<Destination> Destinations { get; set; }
}

public struct Destination
{
    [XmlText()]
    public string Value { get; set; }
}

foreach (Destination destination in config.Export.Destinations)
{
    Console.WriteLine(destination.Value);
}

Upvotes: 2

Related Questions