[Fork] https://stackoverflow.com/questions/53813936/deserialize-an-xml-file-to-object-in-c-sharp

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 NUnit.Framework; //NUnit.Framework.AssertionException

//https://stackoverflow.com/questions/53813936/deserialize-an-xml-file-to-object-in-c-sharp

	[XmlRoot(Namespace = "blabla.xsd", ElementName = "transmission", IsNullable = true)]
	public class Transmission
	{
		[XmlElement("DiagnosisErrorResponse")]
		public DiagnosisErrorResponse DiagnosisErrorResponse { get; set; }
	}

	[XmlRoot(Namespace = "blabla.xsd", IsNullable = true)]
	public class DiagnosisErrorResponse
	{
		[XmlElement("ID")]
		public long ID { get; set; }

		[XmlElement("ErrorCode")]
		public int ErrorCode { get; set; }

		[XmlElement("ErrorDescription")]
		public string ErrorDescription { get; set; }

		[XmlElement("ErrorDate")]
		public string ErrorDate { get; set; }
	}

    public class TestClass
    {
		private DiagnosisErrorResponse ReadXmlFileByPath(string filePath)
		{
			using (var xmlReader = XmlReader.Create(filePath))
			{
				XmlSerializer xs = new XmlSerializer(typeof(Transmission));
				var result = (Transmission)xs.Deserialize(xmlReader);
				return result.DiagnosisErrorResponse;
			}
		}		
		
        public static void Test()
        {
			var filePath = "Question53813936.xml";
			
			Console.WriteLine("Input XML: ");
			Console.WriteLine(XElement.Parse(GetXml()));
			
			File.WriteAllText(filePath, GetXml());
			try
			{
				var result = new TestClass().ReadXmlFileByPath(filePath);
				
				Console.WriteLine("\nDeserialied and re-serialized {0}", result);
				Console.WriteLine(result.GetXml());
				
				Assert.IsTrue(result != null && result.ID == 7 && result.ErrorCode == 9 && result.ErrorDescription == "sometext" && result.ErrorDate == "11-12-2018");
			}
			finally
			{
				File.Delete(filePath);
			}
        }
		
		static string GetXml()
		{
			var xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
   <ns0:transmission xmlns:ns0=""blabla.xsd"">
   <ns0:DiagnosisErrorResponse>
   <ns0:ID>7</ns0:ID>
   <ns0:ErrorCode>9</ns0:ErrorCode>
   <ns0:ErrorDescription>sometext</ns0:ErrorDescription>
   <ns0:ErrorDate>11-12-2018</ns0:ErrorDate>
   </ns0:DiagnosisErrorResponse>
   </ns0:transmission>";
	   		return xml;
		}
    }

    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;
			}
		}
	}
;