Answer the question
In order to leave comments, you need to log in
How to deserialize Nullable types into XML attributes?
Hello. I have a contract like this:
[Serializable]
public class XmlContract
{
[XmlAttribute("ImportantAttribute")]
[DefaultValue(null)]
public decimal? Field { get; set; }
}
[
]IXmlSerializable
[
][
]Answer the question
In order to leave comments, you need to log in
Look in my git, there just zero attributes come from fias. Now I can’t throw off the exact piece from my mobile
Apparently they didn’t search well, or they were looking for some ready-made solutions.
or
[
]
public int? MyNullable{ get; set; }
public bool ShouldSerializeMyNullable()
{
return true;
}
using System;
using System.IO;
using System.Xml.Serialization;
namespace Serialization
{
[Serializable]
public class Person
{
public string Name { get; set; }
public int? Age { get; set; }
public Company Company { get; set; }
public Person()
{ }
public Person(string name, int? age, Company comp)
{
Name = name;
Age = age;
Company = comp;
}
}
[Serializable]
public class Company
{
public string Name { get; set; }
// стандартный конструктор без параметров
public Company() { }
public Company(string name)
{
Name = name;
}
}
class Program
{
static void Main(string[] args)
{
Person person1 = new Person("Tom", 29, new Company("Microsoft"));
Person person2 = new Person("Bill", null, new Company("Apple"));
Person[] people = new Person[] { person1, person2 };
XmlSerializer formatter = new XmlSerializer(typeof(Person[]));
using (FileStream fs = new FileStream("people.xml", FileMode.OpenOrCreate))
{
formatter.Serialize(fs, people);
}
using (FileStream fs = new FileStream("people.xml", FileMode.OpenOrCreate))
{
Person[] newpeople = (Person[])formatter.Deserialize(fs);
foreach (Person p in newpeople)
{
Console.WriteLine($"Имя: {p.Name} --- Возраст: {p.Age?.ToString() ?? "NULL"} --- Компания: {p.Company.Name}");
}
}
Console.ReadLine();
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question