Ciao, se vuoi una serializzazione automatica allora devi mettere gli attributi nella classe :
codice:
[Serializable]
[XmlRoot("Item")]
public class Item
{
[XmlAttribute]
public string Name { get; set; }
public Item() { }
}
[Serializable]
[XmlRoot("Items")]
public class Items : List<Item>
{
public Items() { }
}
...
void Main()
{
Items items = new Items();
items.Add(new Item() { Name = "pippo" });
items.Add(new Item() { Name = "paperino" });
Serialize("test2.txt", items);
items = null;
items = Deserialize("test2.txt");
}
public static bool Serialize(string filename, Items list)
{
bool result = false;
try
{
XmlSerializer x = new XmlSerializer(typeof(Items));
using (TextWriter writer = new StreamWriter(filename))
{
x.Serialize(writer, list);
}
result = true;
}
catch
{
result = false;
}
return result;
}
public static Items Deserialize(string filename)
{
Items result = null;
if (File.Exists(filename))
{
XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Items));
using (Stream strm = File.Open(filename, FileMode.Open))
{
if (strm.Length > 0)
{
try
{
result = (Items)x.Deserialize(strm);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
return result;
}
in questo caso ottieni un xml (che io ho nomimato come txt, ma puoi darli l'estensione xml), come questo :
codice:
<?xml version="1.0" encoding="utf-8"?>
<Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Item Name="pippo" />
<Item Name="paperino" />
</Items>