questions/47993392/alternative-for-deserializing-xml-with-xmlserializer

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;


    // https://stackoverflow.com/questions/47993392/alternative-for-deserializing-xml-with-xmlserializer

    public class Element
    {
        [XmlAttribute]
        public string Name { get; set; }
    }

    class TestClass
    {
        public static void Test()
        {
			var doc = XDocument.Parse(GetXml());

            var list = doc
                // Get the first elements named List
                .Descendants("List").Take(1)
                // Get all children of List named Element
                .SelectMany(l => l.Elements("Element"))
                // Get the attribute of Element named Name, cast its value to a string, 
                // and create a c# Element from it using the specified name.
                .Select(e => new Element { Name = (string)e.Attribute("Name") } )
                // Materialize as a List<Element>
                .ToList();

			list.Dump();
			
			Assert.IsTrue(list.Select(e => e.Name).SequenceEqual(new [] { "A", "B", "C" }));
        }

        static string GetXml()
        {
            var xml = @"<List>
    <Element Name=""A""/>
    <Element Name=""B""/>
    <Element Name=""C""/>
</List> ";
            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));
            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();
                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 static string GetOuterXml(this XmlNode node, bool indent = true)
		{
			if (node == null)
				return null;
			using (var textWriter = new StringWriter())
			{
				var settings = new XmlWriterSettings
				{
					Indent = indent,
					OmitXmlDeclaration = true,
				};
				using (var xmlWriter = XmlWriter.Create(textWriter, settings))
				{
					node.WriteTo(xmlWriter);
				}
				return textWriter.ToString();
			}
		}
    }
										
	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Roslyn 2.0 Compiler; Environment version: " + Environment.Version);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Uncaught exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;