using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var model = new Person() { ID = 1, Name = "Eric", Age = 26, Address = "15F" };
string xml = ObjectXmlSerializer.Serialize<Person>(model);
xml = System.Text.RegularExpressions.Regex.Replace(xml, "^<\?.+\?>", string.Empty);
Console.WriteLine(xml);
Console.ReadLine();
}
}
[Serializable]
[XmlRoot(Namespace = "http://newegg.com/xml")]
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
public class ObjectXmlSerializer
{
public static string Serialize<T>(T t)
{
StringBuilder sb = new StringBuilder();
XmlSerializer xmlSer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StringWriter(sb))
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add("", "http://newegg.com/xml");
xmlSer.Serialize(writer, t, namespaces);
return writer.ToString();
}
}
public static T Deserialize<T>(string str)
{
XmlSerializer xmlSer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(str))
{
T t = (T)xmlSer.Deserialize(reader);
return t;
}
}
}
}