using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; namespace Implab.Xml { public static class SerializationHelpers { public static string SerializeAsString(T obj) { return XmlDefaultSerializer.Instance.SerializeAsString(obj); } public static void Serialize(XmlWriter writer, T obj) { XmlDefaultSerializer.Instance.Serialize(writer, obj); } public static XmlDocument SerializeAsXmlDocument(T obj) { var doc = new XmlDocument(); using (var writer = doc.CreateNavigator().AppendChild()) { XmlDefaultSerializer.Instance.Serialize(writer, obj); } return doc; } public static XDocument SerializeAsXDocument(T obj) { var doc = new XDocument(); using (var writer = doc.CreateWriter()) { XmlDefaultSerializer.Instance.Serialize(writer, obj); } return doc; } public static void SerializeToFile(string file, T obj) { XmlDefaultSerializer.Instance.SerializeToFile(obj, file); } public static void SerializeToElementChild(XmlElement element, T obj) { XmlDefaultSerializer.Instance.Serialize(obj, element); } public static T Deserialize(XmlReader reader) { return (T)XmlDefaultSerializer.Instance.Deserialize(reader); } public static T DeserializeFromFile(string file) { return (T)XmlDefaultSerializer.Instance.DeserializeFromFile(file); } public static T DeserializeFromString(string data) { return (T)XmlDefaultSerializer.Instance.DeserializeFromString(data); } public static T DeserializeFromXmlNode(XmlNode node) { Safe.ArgumentNotNull(node, nameof(node)); using (var reader = node.CreateNavigator().ReadSubtree()) return (T)XmlDefaultSerializer.Instance.Deserialize(reader); } public static T DeserializeJson(TextReader textReader) { var options = new JsonXmlReaderOptions { NamespaceUri = typeof(T).GetCustomAttribute()?.Namespace, RootName = typeof(T).Name, FlattenArrays = true }; using (var reader = JsonXmlReader.CreateJsonXmlReader(textReader, options)) return Deserialize(reader); } public static T DeserializeJsonFromString(string data) { using (var reader = new StringReader(data)) { return DeserializeJson(reader); } } public static void SerializeJson(TextWriter writer, T obj) { var doc = SerializeAsXmlDocument(obj); XmlToJson.Default.Transform(doc, null, writer); } public static string SerializeJsonAsString(T obj) { using (var writer = new StringWriter()) { SerializeJson(writer, obj); return writer.ToString(); } } } }