When deserializing an array in C#, the element is always null.

Forums C#When deserializing an array in C#, the element is always null.
Staff asked 1 year ago

When deserializing partially works, I have an issue. When I have an XML node with attributes, it loads all of the attribute data into my class correctly, but when I utilize elements, it just returns null.

In an XML file, I have the following information:

<?xml version="1.0" encoding="ISO8859-1"?>
    <number id="55">name1</number>
    <number id="4">name2</number>

The following is how the class is defined:

public class root

    [XmlArrayItem(ElementName = "number")]
    public List<NumberObj> numbers { get; set; }

public class NumberObj
    public string name { get; set; }
    public string id { get; set; }    

The name, on the other hand, remains empty. I’ve tried everything from changing the list to an array, but the name is always null.

I can see that the above class is incorrect because I receive the following when I serialize it back to XML:

    <number id="123">
    <number id="45">

Is there anyone that could put me in the correct direction?


Answers (1)

Add Answer
Umang Ramani Marked As Accepted
Staff answered 1 month ago

I believe the right class definition is something like this.

public class Number {
    public string Id { get; set; }
    public string Text { get; set; }

public class Numbers {
    public List<Number> Number { get; set; }



Select Categories