1. Attributs XML
[Serializable]: marque la classe comme sérialisbale.XmlElement: renomme un nœud XML (propriété en élément).XmlRoot: renomme le nœud racine.XmlArray: ajoute un nœud racine autour d'une liste (collection).XmlArrayItem: renomme chaque élément d'une liste.[XmlAttribute("nom")]: la propriété devient un attribut du nœud parent.[XmlIgnore]: ignore la propriété lors de la sérialisation.
Exemple concret avec trois niveaux : ville, district, rue.
[XmlRoot("MyCity", Namespace = "abc.abc", IsNullable = false)]
public class Ville
{
[XmlAttribute("NomVille")]
public string Nom { get; set; }
[XmlAttribute("IdVille")]
public string Id { get; set; }
[XmlArrayAttribute("Districts")]
public District[] Districts { get; set; }
[XmlIgnore]
public string TempInfo { get; set; }
}
[XmlRoot("MonDistrict")]
public class District
{
[XmlAttribute("NomDistrict")]
public string Nom { get; set; }
[XmlElement("IdDistrict", IsNullable = false)]
public string Id { get; set; }
[XmlElement("Rue", IsNullable = false)]
public string[] Rues { get; set; }
}
Génération de données facitces :
static void Main(string[] args)
{
District d1 = new District
{
Nom = "Pudong",
Id = "PD001",
Rues = new[] { "Rue 001", "Rue 002" }
};
District d2 = new District
{
Nom = "Xuhui",
Id = "XH002",
Rues = new[] { "Rue 003", "Rue 004" }
};
Ville v1 = new Ville
{
Nom = "Shanghai",
Id = "SH001",
Districts = new[] { d1, d2 }
};
XmlSerializerHelper.Sauvegarder(@"C:\temp\XML\output003.xml", v1);
}
Fichier XML produit :
<?xml version="1.0" encoding="utf-8"?>
<mycity idville="SH001" nomville="Shanghai" xmlns="abc.abc" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<districts>
<district nomdistrict="Pudong">
<iddistrict>PD001</iddistrict>
<rue>Rue 001</rue>
<rue>Rue 002</rue>
</district>
<district nomdistrict="Xuhui">
<iddistrict>XH002</iddistrict>
<rue>Rue 003</rue>
<rue>Rue 004</rue>
</district>
</districts>
</mycity>
2. Sérialisation et désérialisation XML
public class XmlSerializerHelper
{
public static string Serialiser<T>(T obj)
{
using var sw = new StringWriter();
new XmlSerializer(typeof(T)).Serialize(sw, obj);
return sw.ToString();
}
public static string SerialiserSansDeclaration(object obj)
{
var enc = Encoding.UTF8;
var ser = new XmlSerializer(obj.GetType());
using var ms = new MemoryStream();
var settings = new XmlWriterSettings
{
Indent = true,
NewLineChars = "\r\n",
Encoding = enc,
OmitXmlDeclaration = true,
IndentChars = " "
};
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
using var writer = XmlWriter.Create(ms, settings);
ser.Serialize(writer, obj, ns);
writer.Close();
ms.Position = 0;
using var reader = new StreamReader(ms, enc);
return reader.ReadToEnd();
}
public static T Deserialiser<T>(string xml)
{
var ser = new XmlSerializer(typeof(T));
using var sr = new StringReader(xml);
return (T)ser.Deserialize(sr);
}
}