using System.Collections.Generic;
using System.Xml.Serialization;
public string Value { get; set; }
public XmlNode XmlValue { get => new XmlDocument().CreateCDataSection(Value); set => Value = value?.Value; }
public Info2 Info2 { get; set; }
public string Prop1 { get; set; }
public static void Test()
public static void TestRoot()
Info2 = new() { Prop1 = " prop1 " },
var xml = root.GetXml(omitStandardNamespaces : true);
var root2 = xml.LoadFromXml<Root>();
Console.WriteLine(root2.Value);
Assert.That(root.Value == root2.Value);
Assert.That(root.Info2.Prop1 == root2?.Info2?.Prop1);
public static partial class XmlSerializationHelper
public static T? LoadFromXml<T>(this string xmlString, XmlSerializer? serializer = null)
using (var reader = new StringReader(xmlString))
return (T?)(serializer ?? new(typeof(T))).Deserialize(reader);
public static string GetXml<T>(this T? obj, XmlSerializer? serializer = null, bool indent = true, bool omitStandardNamespaces = false, bool omitXmlDeclaration = false)
XmlSerializerNamespaces? ns = null;
if (omitStandardNamespaces)
using var textWriter = new StringWriter();
var settings = new XmlWriterSettings() { Indent = indent, OmitXmlDeclaration = omitXmlDeclaration };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
(serializer ?? new(obj?.GetType() ?? typeof(T))).Serialize(xmlWriter, obj, ns);
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("Uncaught exception: ");