using System.Collections.Generic;
using System.Xml.Serialization;
[XmlElement(IsNullable = false)]
public int? Foo { get; set; }
public string? Bar { get; set; }
public static void Test()
var obj = new SomeObject();
public static class XmlSerializationHelper
public static T? LoadFromXml<T>(this string xmlString, XmlSerializer? serial = null)
using (var reader = new StringReader(xmlString))
return (T?)(serial ?? new XmlSerializer(typeof(T))).Deserialize(reader);
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() ?? typeof(T))).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 class XmlAssert
public static void AreEqual(
Assert.IsTrue(XNode.DeepEquals(Normalize(expected), Normalize(actual)));
private static XElement Normalize(XElement element)
.OrderBy(a => a.Name.ToString()),
.OrderBy(a => a.Name.ToString())
.Select(e => Normalize(e)));
.OrderBy(a => a.Name.ToString()));
return new XElement(element.Name, element.Attributes()
.OrderBy(a => a.Name.ToString()), element.Value);
public static void Main()
Console.WriteLine("Environment version: {0} ({1}, {2}, NewLine: {3}).",
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion,
System.Text.Json.JsonSerializer.Serialize(Environment.NewLine));
Console.WriteLine("Failed with unhandled exception: ");