I have a List of Book in an XML file. Book has a property List<string> Authors:
public List<string> Authors
{
get => _authors;
set
{
if (value == null) throw new ArgumentNullException(nameof(value));
_authors = value.Any()
? value : throw new ArgumentOutOfRangeException(nameof(value), @"Must have at least one author.");
}
}
So, as I understand, when I deserialize it with XmlSerializer, it tries to give the property an empty list first and then to fill it with values, which doen's work, because the setter throws an exception. What may be a solution here?
Deserialization:
using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var xmlSerializer = new XmlSerializer(typeof(List<Book>));
data = (List<Book>)xmlSerializer.Deserialize(fileStream);
upd: XML
<?xml version="1.0"?>
<ArrayOfBook xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Book>
<Id>0</Id>
<Name>Unspecified</Name>
<YearPublished>2000</YearPublished>
<PagesNumber>200</PagesNumber>
<Annotation>No annotation.</Annotation>
<Price>50</Price>
<StandardNumber>1</StandardNumber>
<Authors>
<string>Author1</string>
</Authors>
<CityPublished>Unspecified</CityPublished>
<Publisher>Unspecified</Publisher>
<CopiesNumber>300</CopiesNumber>
</Book>
<Book>
<Id>0</Id>
<Name>Unspecified</Name>
<YearPublished>2000</YearPublished>
<PagesNumber>200</PagesNumber>
<Annotation>No annotation.</Annotation>
<Price>50</Price>
<StandardNumber>2</StandardNumber>
<Authors>
<string>Author2</string>
</Authors>
<CityPublished>Unspecified</CityPublished>
<Publisher>Unspecified</Publisher>
<CopiesNumber>300</CopiesNumber>
</Book>
<Book>
<Id>0</Id>
<Name>Unspecified</Name>
<YearPublished>2000</YearPublished>
<PagesNumber>200</PagesNumber>
<Annotation>No annotation.</Annotation>
<Price>50</Price>
<StandardNumber>3</StandardNumber>
<Authors>
<string>Author3</string>
</Authors>
<CityPublished>Unspecified</CityPublished>
<Publisher>Unspecified</Publisher>
<CopiesNumber>300</CopiesNumber>
</Book>
</ArrayOfBook>
upd2: Chosen solution
[XmlIgnore]
[JsonIgnore]
[IgnoreDataMember]
public List<string> Authors
{
get => new(_authors);
set
{
if (value == null) throw new ArgumentNullException(nameof(value));
_authors = value.Any()
? value : throw new ArgumentOutOfRangeException(nameof(value), @"Must have at least one author.");
}
}
[XmlArray(nameof(Authors))]
[JsonProperty(nameof(Authors))]
public string[] AuthorsArray
{
get => Authors.ToArray();
set
{
if (value == null || !value.Any()) return;
if (_authors == null)
{
Authors = new List<string>(value);
}
else
{
Authors.AddRange(value);
}
}
}