public static T Read <T>(XmlReader reader, T obj) where T : IXmlSerializable { if (reader.IsEmptyElement == false) { reader.ReadStartElement(); reader.MoveToContent(); var o = typeof(T).IsClass == true ? obj : (object)Activator.CreateInstance(typeof(T)); while (reader.NodeType == XmlNodeType.Element) { var property = typeof(T).GetProperty(reader.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var value = IXmlSerializableUtility.ReadElement(reader, property.PropertyType); property.SetValue(o, value); } reader.MoveToContent(); reader.ReadEndElement(); return((T)o); } else { reader.Skip(); return(obj); } }
//public static T Read<T>(XmlReader reader) where T : struct, IXmlSerializable //{ // reader.ReadStartElement(); // reader.MoveToContent(); // var properties = TypeDescriptor.GetProperties(typeof(T)); // var obj = (object)Activator.CreateInstance(typeof(T)); // while (reader.NodeType == XmlNodeType.Element) // { // var property = properties[reader.Name]; // var value = IXmlSerializableUtility.ReadElement(reader, property.PropertyType); // property.SetValue(obj, value); // } // reader.MoveToContent(); // reader.ReadEndElement(); // return (T)obj; //} public static object ReadElement(XmlReader reader, Type type) { var value = null as object; if (reader.IsEmptyElement == false) { reader.ReadStartElement(reader.Name); if (type == typeof(byte[])) { var buffer = new byte[1024]; using (var stream = new MemoryStream()) { var readBytes = 0; while ((readBytes = reader.ReadContentAsBinHex(buffer, 0, 1024)) > 0) { stream.Write(buffer, 0, readBytes); } stream.Position = 0; buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); } value = buffer; reader.MoveToContent(); } else if (type.IsArray == true) { var itemList = new List <object>(); while (reader.NodeType == XmlNodeType.Element) { var itemType = type.GetElementType(); if (reader.HasAttributes == true) { var typeName = reader.GetAttribute("type"); if (typeName != null) { itemType = Type.GetType(typeName); } } var item = IXmlSerializableUtility.ReadElement(reader, itemType); itemList.Add(item); } var arrayList = Array.CreateInstance(type.GetElementType(), itemList.Count); for (var i = 0; i < itemList.Count; i++) { arrayList.SetValue(itemList[i], i); } value = arrayList; } else if (XmlConvertUtility.IsBaseType(type) == true) { value = XmlConvertUtility.ToValue(reader.ReadContentAsString(), type); } else { value = XmlSerializerUtility.Read(reader, type); } reader.ReadEndElement(); } else { if (type.IsArray == true) { value = Array.CreateInstance(type.GetElementType(), 0); } reader.Skip(); } reader.MoveToContent(); return(value); }