using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace XmlSerializeDemo
{
[XmlRoot("TechTree")]
public class TechCollection
{
[XmlAttribute("version")]
public int Version { get; set; }
[XmlElement("Tech")]
public TechItem Item { get; set; }
}
public class TechItem
{
[XmlAttribute("type")]
public string Type { get; set; }
[XmlAttribute("name")]
public string Name { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
var e = new TechItem() { Type = "Noraml", Name = "Age 1" };
var t = new TechCollection() { Version = 5, Item = e };
Serialize(@".\demo.xml", t);
}
private static void Serialize<T>(string path, T obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = ConformanceLevel.Document;
settings.OmitXmlDeclaration = false; // не подавлять xml заголовок
settings.Encoding = Encoding.UTF8; // кодировка
settings.Indent = true; // добавлять отступы
settings.IndentChars = " "; // сиволы отступа
// подавляем неймспейсы
XmlSerializerNamespaces dummyNSs = new XmlSerializerNamespaces();
dummyNSs.Add(string.Empty, string.Empty);
using (FileStream fileStream = new FileStream(path, FileMode.Create))
{
using (XmlWriter xw = XmlWriter.Create(fileStream, settings))
{
serializer.Serialize(xw, obj, dummyNSs);
}
}
}
}
}
на выходе
<?xml version="1.0" encoding="utf-8"?>
<TechTree version="5">
<Tech type="Noraml" name="Age 1" />
</TechTree>