假设您有一个Player类,如下所示:
[XmlRoot]
public class Player
{
[XmlElement]
public int Level { get; set; }
[XmlElement]
public int Health { get; set; }
}
这是一个完整的往返旅程,可以帮助您入门:
XmlSerializer xmls = new XmlSerializer(typeof(Player));
StringWriter sw = new StringWriter();
xmls.Serialize(sw, new Player { Level = 5, Health = 500 });
string xml = sw.ToString();
Player player = xmls.Deserialize(new StringReader(xml)) as Player;
xml是:
<?xml version="1.0" encoding="utf-16"?>
<Player xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Level>5</Level>
<Health>500</Health>
</Player>
而且你猜player和我们序列化的原始对象完全一样。
如果要从文件序列化/反序列化,可以执行以下操作:
using (var stream = File.OpenWrite("my_player.xml"))
{
xmls.Serialize(stream, new Player { Level = 5, Health = 500 });
}
Player player = null;
using (var stream = File.OpenRead("my_player.xml"))
{
player = xmls.Deserialize(stream) as Player;
}
编辑:
如果您想要您显示的 XML:
XmlSerializer xmls = new XmlSerializer(typeof(Player));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };
using (var stream = File.OpenWrite("my_player.xml"))
{
using (var xmlWriter = XmlWriter.Create(stream, settings))
{
xmls.Serialize(xmlWriter, new Player { Level = 5, Health = 500 }, ns);
}
}
Player player = null;
using (var stream = File.OpenRead("my_player.xml"))
{
player = xmls.Deserialize(stream) as Player;
}