using System.Text; using System.Xml; using System.Xml.Serialization; var p = new Person { Id = 1, Name = "Furion", Items = new List<string> { "Furion", "百小僧" } }; var xml = XmlSerialize(p); Console.ReadKey(); static string XmlSerialize(object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); var xs = new XmlSerializer(obj.GetType()); using var stream = new MemoryStream(); var setting = new XmlWriterSettings { Encoding = new UTF8Encoding(false), Indent = true }; using var writer = XmlWriter.Create(stream, setting); var ns = new XmlSerializerNamespaces(); ns.Add(string.Empty, string.Empty); xs.Serialize(writer, obj, ns); return Encoding.UTF8.GetString(stream.ToArray()); } [XmlRoot("person")] public class Person { [XmlAttribute("id")] public int Id { get; set; } [XmlElement("name")] public string Name { get; set; } [XmlArray("items")] [XmlArrayItem("item")] public List<string> Items { get; set; } }
https://www.cnblogs.com/goody9807/p/3934892.html
标签:xml,obj,string,using,var,new,序列化,public From: https://www.cnblogs.com/baiqian/p/17363378.html