直接上代码
using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; using System.Text.RegularExpressions; using System.Dynamic; namespace ConsoleApplication7 { public class Test { public TestDy TestDy { get; set; } } public class TestDy : DynamicObject, IXmlSerializable { public override bool TryGetMember(GetMemberBinder binder, out object result) { string name = binder.Name.ToLower(); bool exist = Dict.TryGetValue(name, out result); if (!exist) { // 不存在,默认空 result = null; } return true; } public override bool TrySetMember(SetMemberBinder binder, object value) { Dict[binder.Name.ToLower()] = value; return true; } Dictionary<string, object> Dict = new Dictionary<string, object>(); public string Sid { get; set; } public XmlSchema GetSchema() { return (null); } public void ReadXml(XmlReader reader) { Sid = reader.ReadString(); } public void WriteXml(XmlWriter writer) { writer.WriteStartElement("Sid"); writer.WriteAttributeString("id", Sid.ToString()); foreach (var item in Dict) { writer.WriteAttributeString(item.Key, item.Value.ToString()); } writer.WriteEndElement(); } } public class XML { public static string XmlSerialize(Type type, object obj) { MemoryStream Stream = new MemoryStream(); XmlSerializer xml = new XmlSerializer(type); try { xml.Serialize(Stream, obj); } catch (InvalidOperationException) { throw; } Stream.Position = 0; StreamReader sr = new StreamReader(Stream); string str = sr.ReadToEnd(); sr.Dispose(); Stream.Dispose(); return str; } public static string SerializeXml(object value) { XmlSerializer serializer = new XmlSerializer(value.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.Serialize(ms, value); ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms)) { return sr.ReadToEnd(); } } } public static string XmlSerialize<T>(T obj) { XmlSerializer serializer = new XmlSerializer(typeof(T)); MemoryStream mem = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); serializer.Serialize(writer, obj, ns); writer.Close(); return Encoding.UTF8.GetString(mem.ToArray()); } } public class Program { static void Main(string[] args) { var test = new Test(); dynamic dy = new TestDy(); test.TestDy = dy; //dynamic dy = new TestDy(); dy.Sid = "9527"; dy.属性1 = "123"; dy.属性2 = "456"; dy.属性3 ="789"; TextWriter writer = new StreamWriter("C:\\Users\\LYY\\Desktop\\Test.xml"); //string strxml = XML.XmlSerialize(test); //string strxml = XML.XmlSerialize<Test>(test); //writer.WriteLine(strxml); XmlSerializer serializer = new XmlSerializer(test.GetType()); serializer.Serialize(writer,test); writer.Close(); } } }