using System.Collections.Generic;
using System.Xml.Serialization;
[XmlRoot("Histogram", Namespace = "Ala ma kota")]
[XmlType(Namespace = "")]
public Data Data { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public static partial class XmlSerializationExtensions
public static T? Deserialize<T>(this XContainer element, XmlSerializer? serializer = null)
using (var reader = element.CreateReader())
return (T?)(serializer ?? new XmlSerializer(typeof(T))).Deserialize(reader);
public static void Test()
var outerXmlString = GetXml();
var doc = XDocument.Parse(outerXmlString);
XNamespace ns = "Ala ma kota";
var element = doc.Descendants(ns + "Histogram").FirstOrDefault();
var histogram = element?.Deserialize<Histogram>();
Console.WriteLine(element?.ToString());
Console.WriteLine($"\nRe-serialized {histogram}:");
Console.WriteLine(histogram.GetXml(omitStandardNamespaces : true));
static string GetXml() =>
<Root xmlns:c="Ala ma kota">
<Data Width="10" Height="20" />
public static partial class XmlSerializationHelper
public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
serial = serial ?? new XmlSerializer(typeof(T));
using (var reader = new StringReader(xmlString))
return (T)serial.Deserialize(reader);
public static string GetXml<T>(this T obj, bool omitStandardNamespaces)
return obj.GetXml(null, omitStandardNamespaces);
public static string GetXml<T>(this T obj, XmlSerializer serializer = null, bool omitStandardNamespaces = false)
XmlSerializerNamespaces ns = null;
if (omitStandardNamespaces)
ns = new XmlSerializerNamespaces();
using (var textWriter = new StringWriter())
var settings = new XmlWriterSettings() { Indent = true };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
(serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();
public static string GetOuterXml(this XmlNode node, bool indent = true)
using (var textWriter = new StringWriter())
var settings = new XmlWriterSettings
OmitXmlDeclaration = true,
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
return textWriter.ToString();
public static void Main()
Console.WriteLine("Environment version: {0} ({1}, {2})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("Failed with unhandled exception: ");