Omer Kahoot
Omer Kahoot

Reputation: 144

Deserializing XML Into class with different members C#

I am facing a problem in deserializing xml into a class object. The class has a slightly different structure than the xml, so am unable to deserialize it. Following is the main code

public class Customer
{
    [XmlElement(ElementName = "CustomerName")]
    public string Name { get; set; }
}

public class XmlCheck
{
    [XmlElement(ElementName = "Customer")]
    public Customer Customer { get; set; }

    public List<Customer> CustomersList { get; set; }
}

class Program
{
    static string xml = @"<?xml version=""1.0"" ?>
    <XmlCheck>
    <Customer>
    <CustomerName>Omer</CustomerName>
    </Customer>
    <Customer>
    <CustomerName>Ali</CustomerName>
    </Customer>
    </XmlCheck>";

    static void Main(string[] args)
    {
        var serializer = new XmlSerializer(typeof(XmlCheck), new XmlRootAttribute("XmlCheck"));
        using (var stringReader = new StringReader(xml))
        using (var reader = XmlReader.Create(stringReader))
        {
            var xmlResult = (XmlCheck)serializer.Deserialize(reader);
            xmlResult.CustomersList.Add(xmlResult.Customer);
            Console.WriteLine(xmlResult.Customer.Name);
        }
    }

Is there any way, to deserialize the xml into the customers list without having to insert that node inside the xml? Currently this only deserializes the first customer node that has name as 'Omer' and it adds that to the list.

I know how to accomplish the above by writing a custom xml reader, but need to use xml deserialization for this. However, if this isn't possible using xml deserialization, any way to achieve this using any customer (s/de)erializer?

Upvotes: 1

Views: 976

Answers (1)

Lucian
Lucian

Reputation: 3554

Please try this:

public class Customer
{
    [XmlElement(ElementName = "CustomerName")]
    public string Name { get; set; }
}

[XmlRoot("XmlCheck")]
public class XmlCheck
{

    [XmlElement(ElementName = "Customer")]
    public List<Customer> CustomersList { get; set; }
}

class Program
{
    static string xml = @"<?xml version=""1.0"" ?>
<XmlCheck>
<Customer>
<CustomerName>Omer</CustomerName>
</Customer>
<Customer>
<CustomerName>Ali</CustomerName>
</Customer>
</XmlCheck>";

    static void Main(string[] args)
    {
        var serializer = new XmlSerializer(typeof(XmlCheck), new XmlRootAttribute("XmlCheck"));
        using (var stringReader = new StringReader(xml))
        using (var reader = XmlReader.Create(stringReader))
        {
            var xmlResult = (XmlCheck)serializer.Deserialize(reader);
            //xmlResult.CustomersList.Add(xmlResult.Customer);
            foreach(var c in xmlResult.CustomersList)
            {
                Console.WriteLine(c.Name);
            }
        }
    }
}

I got it from: Is it possible to deserialize XML into List<T>?

Upvotes: 1

Related Questions