Created
November 12, 2025 11:32
-
-
Save sunmeat/4c45169194beb2ed2c5e7f559dfa7eab to your computer and use it in GitHub Desktop.
XML serialization C# example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Xml.Serialization; | |
| namespace XMLSerializerExample | |
| { | |
| [Serializable] | |
| public class Human | |
| { | |
| public string? Name { get; set; } | |
| [XmlIgnore] | |
| public int Age { get; set; } | |
| } | |
| [Serializable] | |
| public class SuperHero : Human | |
| { | |
| public bool IsEvil { get; set; } | |
| public Ability Superpower { get; set; } = new Ability(); | |
| } | |
| [Serializable] | |
| public class Ability | |
| { | |
| public bool IsUnique { get; set; } | |
| public string[]? Abilities { get; set; } | |
| } | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| System.Console.OutputEncoding = System.Text.Encoding.UTF8; | |
| string filePath = "test.xml"; | |
| var hero = new SuperHero(); | |
| hero.Name = "Хронічний Рефлюкс"; | |
| hero.Age = 36; | |
| hero.IsEvil = false; | |
| hero.Superpower.Abilities = new string[] { "гострий зір", | |
| "невидимість", "телекинез", "генерація кислоти", | |
| "телепортація", "воскресіння", "маніпуляція часом" }; | |
| hero.Superpower.IsUnique = true; | |
| var serializer = new XmlSerializer(typeof(SuperHero)); | |
| // створює новий потік файлу для запису серіалізованого об'єкта у файл | |
| var write = new StreamWriter(filePath); | |
| serializer.Serialize(write, hero); // !!! | |
| write.Close(); | |
| // створює новий потік файлу для читання xml-файлу | |
| var read = new FileStream(filePath, FileMode.Open, FileAccess.Read); | |
| // завантажує об'єкт, збережений вище, за допомогою deserialize | |
| var copy = (SuperHero)serializer.Deserialize(read); // !!! | |
| read.Close(); | |
| // зауважте: вік не серіалізується через xmlignore, тому буде 0 після десеріалізації | |
| System.Console.WriteLine("Ім'я:\t\t" + copy?.Name); | |
| System.Console.WriteLine("Вік:\t\t" + copy?.Age); | |
| System.Console.WriteLine("Чи злий:\t" + copy?.IsEvil); | |
| System.Console.WriteLine("Чи унікальний:\t" + copy?.Superpower.IsUnique); | |
| System.Console.WriteLine("\nСписок навичок:"); | |
| foreach (var skill in copy?.Superpower.Abilities ?? new string[0]) | |
| { | |
| System.Console.WriteLine("\t" + skill); | |
| } | |
| // очищає тимчасовий файл після використання | |
| // File.Delete(filePath); // перевірити наявність файла в папці проєкта | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment