https://stackoverflow.com/questions/61190548/deserialize-comments-using-custom-ixmlserializer

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
using System.Reflection;
using System.Configuration;
using System.ComponentModel;
using System.Xml.Schema;

using NUnit.Framework; //NUnit.Framework.AssertionException

    // https://stackoverflow.com/questions/61190548/deserialize-comments-using-custom-ixmlserializer
    // https://stackoverflow.com/questions/61190548/deserialize-comments-using-custom-ixmlserializer

    [Serializable]
    public sealed class Setting<T> : SettingBase, IXmlSerializable
    {
        public Setting() { }

        public Setting(T value, string description)
        {
            Value = value;
            Description = description;
        }

        public Setting(string command, T value, string description)
            : this(value, description)
        {
            Command = command;
        }

        public XmlSchema GetSchema() { return null;}

        public void ReadXml(XmlReader reader)
        {
            XmlSerializationExtensions.ReadIXmlSerializable(reader, r => true,
                r =>
                {
                    switch (r.LocalName)
                    {
                        case "Command":
                            Command = r.ReadElementContentAsString();
                            break;
                        case "Value":
                            var serializer = XmlSerializerFactory.Create(typeof(T), "Value", reader.NamespaceURI);
                            Value = (T)serializer.Deserialize(r);
                            break;
                    }
                    return true;
                },
                r => true, r => { Description += r.Value; return true; });
        }

        public void WriteXml(XmlWriter writer)
        {
            XmlSerializationExtensions.WriteIXmlSerializable(writer, w => { },
                w =>
                {
                    if (Description != null)
                        w.WriteComment(Description);
                    if (Command != null)
                        w.WriteElementString("Command", Command);
                    if (Value != null)
                    {
                        var serializer = XmlSerializerFactory.Create(typeof(T), "Value", null);
                        serializer.Serialize(w, Value);
                    }
                });
        }


        public string Description { get; set; }

        public string Command { get; set; }

        public T Value { get; set; }

        public override object ValueUntyped { get { return Value; } }
    }

    // ABSTRACT BASE CLASS NOT INCLUDED IN QUESTION, THIS IS JUST A GUESS
    [Serializable]
    public abstract class SettingBase
    {
        public abstract object ValueUntyped { get; }
    }

    public static class XmlSerializationExtensions
    {
        // Adapted from this answer https://stackoverflow.com/a/60498500/3744182
        // To https://stackoverflow.com/questions/60449088/why-does-xmlserializer-throws-an-exception-and-raise-a-validationevent-when-a-sc
        // by handling comments.
        public static void ReadIXmlSerializable(XmlReader reader, Func<XmlReader, bool> handleXmlAttribute, Func<XmlReader, bool> handleXmlElement, Func<XmlReader, bool> handleXmlText, Func<XmlReader, bool> handleXmlComment)
        {
            //https://docs.microsoft.com/en-us/dotnet/api/system.xml.serialization.ixmlserializable.readxml?view=netframework-4.8#remarks
            //When this method is called, the reader is positioned on the start tag that wraps the information for your type. 
            //That is, directly on the start tag that indicates the beginning of a serialized object. 
            //When this method returns, it must have read the entire element from beginning to end, including all of its contents. 
            //Unlike the WriteXml method, the framework does not handle the wrapper element automatically. Your implementation must do so. 
            //Failing to observe these positioning rules may cause code to generate unexpected runtime exceptions or corrupt data.
            reader.MoveToContent();
            if (reader.NodeType != XmlNodeType.Element)
                throw new XmlException(string.Format("Invalid NodeType {0}", reader.NodeType));
            if (reader.HasAttributes)
            {
                for (int i = 0; i < reader.AttributeCount; i++)
                {
                    reader.MoveToAttribute(i);
                    handleXmlAttribute(reader);
                }
                reader.MoveToElement(); // Moves the reader back to the element node.
            }
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return;
            }
            reader.ReadStartElement(); // Advance to the first sub element of the wrapper element.
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    using (var subReader = reader.ReadSubtree())
                    {
                        subReader.MoveToContent();
                        handleXmlElement(subReader);
                    }
                    // ReadSubtree() leaves the reader positioned ON the end of the element, so read that also.
                    reader.Read();
                }
                else if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
                {
                    var type = reader.NodeType;
                    handleXmlText(reader);
                    // Ensure that the reader was not advanced.
                    if (reader.NodeType != type)
                        throw new XmlException(string.Format("handleXmlText incorrectly advanced the reader to a new node {0}", reader.NodeType));
                    reader.Read();
                }
                else if (reader.NodeType == XmlNodeType.Comment)
                {
                    var type = reader.NodeType;
                    handleXmlComment(reader);
                    // Ensure that the reader was not advanced.
                    if (reader.NodeType != type)
                        throw new XmlException(string.Format("handleXmlComment incorrectly advanced the reader to a new node {0}", reader.NodeType));
                    reader.Read();
                }
                else // Whitespace, etc.
                {
                    // Skip() leaves the reader positioned AFTER the end of the node.
                    reader.Skip();
                }
            }
            // Move past the end of the wrapper element
            reader.ReadEndElement();
        }

        public static void ReadIXmlSerializable(XmlReader reader, Func<XmlReader, bool> handleXmlAttribute, Func<XmlReader, bool> handleXmlElement, Func<XmlReader, bool> handleXmlText)
        {
            ReadIXmlSerializable(reader, handleXmlAttribute, handleXmlElement, handleXmlText, r => true);
        }

        public static void WriteIXmlSerializable(XmlWriter writer, Action<XmlWriter> writeAttributes, Action<XmlWriter> writeNodes)
        {
            //https://docs.microsoft.com/en-us/dotnet/api/system.xml.serialization.ixmlserializable.writexml?view=netframework-4.8#remarks
            //The WriteXml implementation you provide should write out the XML representation of the object. 
            //The framework writes a wrapper element and positions the XML writer after its start. Your implementation may write its contents, including child elements. 
            //The framework then closes the wrapper element.
            writeAttributes(writer);
            writeNodes(writer);
        }
    }

    public static class XmlSerializerFactory
    {
        // To avoid a memory leak the serializer must be cached.
        // https://stackoverflow.com/questions/23897145/memory-leak-using-streamreader-and-xmlserializer
        // This factory taken from 
        // https://stackoverflow.com/questions/34128757/wrap-properties-with-cdata-section-xml-serialization-c-sharp/34138648#34138648

        readonly static Dictionary<Tuple<Type, string, string>, XmlSerializer> cache;
        readonly static object padlock;

        static XmlSerializerFactory()
        {
            padlock = new object();
            cache = new Dictionary<Tuple<Type, string, string>, XmlSerializer>();
        }

        public static XmlSerializer Create(Type serializedType, string rootName, string rootNamespace)
        {
            if (serializedType == null)
                throw new ArgumentNullException();
            if (rootName == null && rootNamespace == null)
                return new XmlSerializer(serializedType);
            lock (padlock)
            {
                XmlSerializer serializer;
                var key = Tuple.Create(serializedType, rootName, rootNamespace);
                if (!cache.TryGetValue(key, out serializer))
                    cache[key] = serializer = new XmlSerializer(serializedType, new XmlRootAttribute { ElementName = rootName, Namespace = rootNamespace });
                return serializer;
            }
        }
    }

	[XmlRoot("Wrapper", Namespace = "questions/61190548")]
	public class Wrapper<T>
	{
		[XmlElement(Order = 1)]
		public Setting<T> Setting { get; set; }
		[XmlElement(Order = 2)]
		public string Text { get; set; }
	}
		
    class TestClass
    {
        public static void Test()
        {
            Test("my setting value", EqualityComparer<string>.Default.Equals);
            Test(new DateTime(2020, 4, 13, 10, 10, 10), EqualityComparer<DateTime>.Default.Equals);
            Test(10101.01m, EqualityComparer<decimal>.Default.Equals);
            Test(new[] { "string1", "string2" }, (x, y) => x.SequenceEqual(y));
        }

        static void Test<T>(T value, Func<T, T, bool> equals)
		{
            Console.WriteLine("\nTesting {0} {1}:", typeof(T), value);
        	TestAsRoot(value, equals);
			TestNested(value, equals);
		}
		
        static void TestAsRoot<T>(T value, Func<T, T, bool> equals)
        {
            var setting = new Setting<T>("my command", value, "my description");

            var xml = setting.GetXml();

            Console.WriteLine(xml);

            var setting2 = xml.LoadFromXml<Setting<T>>();

            var xml2 = setting2.GetXml();

            Console.WriteLine(xml2);

            Assert.IsTrue(equals(setting.Value, setting2.Value));
            Assert.IsTrue(setting.Description == setting2.Description);
            Assert.IsTrue(setting.Command == setting2.Command);
			Assert.IsTrue(xml == xml2);
        }
		
		static void TestNested<T>(T value, Func<T, T, bool> equals)
		{
            var setting = new Setting<T>("my command", value, "my description");
			var root = new Wrapper<T> { Setting = setting, Text = "Wrapper Text" };

            var xml = root.GetXml();

            Console.WriteLine(xml);

            var root2 = xml.LoadFromXml<Wrapper<T>>();
			var setting2 = root2.Setting;

            var xml2 = root2.GetXml();

            Console.WriteLine(xml2);

            Assert.IsTrue(equals(setting.Value, setting2.Value));
            Assert.IsTrue(setting.Description == setting2.Description);
            Assert.IsTrue(setting.Command == setting2.Command);
			Assert.IsTrue(xml == xml2);
			Assert.IsTrue(root.Text == root2.Text);
		}
    }

	public static 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, XmlSerializer serializer = null, bool omitStandardNamespaces = false)
        {
            XmlSerializerNamespaces ns = null;
            if (omitStandardNamespaces)
            {
                ns = new XmlSerializerNamespaces();
                ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
            }			
            using (var textWriter = new StringWriter())
            {
                var settings = new XmlWriterSettings() { Indent = true }; // For cosmetic purposes.
                using (var xmlWriter = XmlWriter.Create(textWriter, settings))
                    (serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj, ns);
                return textWriter.ToString();
            }
        }
    }

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
		
		public static string GetNetCoreVersion()
		{
			//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
			//
			var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
			var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
			int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
			if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
				return assemblyPath[netCoreAppIndex + 1];
			return null;
		}
	}
;