questions/46653819/deserialize-xml-into-a-class-with-different-hierarchy

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Threading;
using System.ComponentModel;
using System.Xml.Linq;
using System.Reflection;
using System.Data;
using System.Xml.Schema;
using System.Text.RegularExpressions;
using System.Net;
using System.Xml.XPath;
using System.Globalization;
using System.ComponentModel.DataAnnotations;
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;

// https://stackoverflow.com/questions/46653819/deserialize-xml-into-a-class-with-different-hierarchy

    public static class XmlModelSerializer<TRoot>
    {
        static XmlSerializer alternateSerializerInstance;
        static XmlSerializer currentSerializerInstance;

        public static XmlSerializer AlternateSerializerInstance { get { return alternateSerializerInstance; } }

        public static XmlSerializer CurrentSerializerInstance { get { return currentSerializerInstance; } }

        static XmlModelSerializer()
        {
            XmlAttributes alternateAttributes = new XmlAttributes
            {
                XmlElements = { new XmlElementAttribute("bar") },
            };
            XmlAttributeOverrides alternateOverrides = new XmlAttributeOverrides();
            alternateOverrides.Add(typeof(XmlModel), "Foo", alternateAttributes);
            alternateSerializerInstance = new XmlSerializer(typeof(TRoot), alternateOverrides);

            XmlAttributes currentAttributes = new XmlAttributes
            {
                XmlArray = new XmlArrayAttribute("foo"),
                XmlArrayItems = { new XmlArrayItemAttribute("bar") },
            };
            XmlAttributeOverrides currentOverrides = new XmlAttributeOverrides();
            currentOverrides.Add(typeof(XmlModel), "Foo", currentAttributes);
            currentSerializerInstance = new XmlSerializer(typeof(TRoot), currentOverrides);
        }
    }

    [XmlRoot("root")]
    public class XmlModel
    {
        [XmlArray("foo")]
        [XmlArrayItem("bar")]
        public List<string> Foo { get; set; }
    }

    class TestClass
    {
        public static void Test()
        {
            Test(XmlModelSerializer<XmlModel>.CurrentSerializerInstance, GetXmlModelXml());
            Test(XmlModelSerializer<XmlModel>.AlternateSerializerInstance, GetAlternateXml());

            Console.WriteLine("\nDone.");
        }

        public static void Test(XmlSerializer serializer, string xml)
        {
            Console.WriteLine("\nDeserializing XML: ");
            Console.WriteLine(xml);

            var model = xml.LoadFromXml<XmlModel>(serializer);

            var xml2 = model.GetXml(true);

            Console.WriteLine("Re-serialized {0}", model);
            Console.WriteLine(xml2);

            Assert.IsTrue(XDocument.Parse(xml).XPathSelectElements("//bar").Select(e => (string)e).SequenceEqual(model.Foo));
        }

        static string GetXmlModelXml()
        {
            string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
            <root>
                <foo>
                    <bar>1</bar>
                    <bar>2</bar>
                </foo>
            </root>";

            return xml;
        }

        static string GetAlternateXml()
        {
            string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<root>
    <bar>1</bar>
    <bar>2</bar>
</root>"; 
            return xml;
        }
    }

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }

    public static class XmlSerializationHelper
    {
        public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
        {
            serial = serial ?? new XmlSerializer(typeof(T));
            T returnValue = default(T);
            using (StringReader reader = new StringReader(xmlString))
            {
                object result = serial.Deserialize(reader);
                if (result is T)
                {
                    returnValue = (T)result;
                }
            }
            return returnValue;
        }

        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();
                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: " + Environment.Version);
			Console.WriteLine();

			TestClass.Test();
		}
	}
;