1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace object2xml { public static class XmlExtension { public static string Serialize<T>(this T value) { if (value == null) return string.Empty; var xmlserializer = new XmlSerializer(typeof(T)); using (StringWriter stringWriter = new StringWriter()) { using (var writer = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true })) { xmlserializer.Serialize(writer, value); return stringWriter.ToString(); } } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace object2xml { public class Persion { public string Name { get; set; public int Age { get; set; } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace object2xml { class Program { static void Main(string[] args) { Persion p = new Persion(); p.Name = "张三"; p.Age = 18; var xml = p.Serialize<Persion>(); Console.WriteLine(xml); } } } |
from:https://blog.csdn.net/justgono/article/details/45887619