questions/49317672/class-properties-ignored-by-xmlserializer

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
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;

// https://stackoverflow.com/questions/49317672/class-properties-ignored-by-xmlserializer

	[XmlType("Edition")]
	public class Book 
	{
		#region Attributes
		private string series;
		private string title;
		private string isbn;
		private string pubDate;
		#endregion Attributes
	
		#region Encapsulated fields
		[XmlElement]
		public string Series { get => series; set => series = value; }
		
		[XmlElement]
		public string Title { get => title; set => title = value; }

		[XmlElement("ISBN")]
		public string Isbn { get => isbn; set => isbn = value; }

		[XmlElement("Publication_Date")]
		public string EditionPubDate { get => pubDate; set => pubDate = value; }

		#endregion Encapsulated fields
	
		#region Constructors
		public Book() { }
		#endregion Constructors
	
		#region Methods
		public XmlElement SerializeToXmlElement()
		{
			XmlDocument doc = new XmlDocument();
			using (XmlWriter writer = doc.CreateNavigator().AppendChild())
			{
                var ns = new XmlSerializerNamespaces();
                ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
				new XmlSerializer(this.GetType()).Serialize(writer, this, ns);
			}
			return doc.DocumentElement;
		}
		#endregion Methods
	}

    public class TestClass
    {
        public static void Test()
        {
			Book b = new Book();
			b.Isbn = "978-0-553-10953-5";
			b.Title = "A Brief History of Time";
			var element = b.SerializeToXmlElement();
			
			//Console.WriteLine(element.GetOuterXml());
			
			XmlDocument doc = new XmlDocument();
			doc.AppendChild(doc.CreateXmlDeclaration("1.0","utf-8",null));
			XmlNode rootnode = doc.AppendChild(doc.CreateElement("Root_Node"));
			XmlNode editionsNode = rootnode.AppendChild(doc.CreateElement("Editions"));
			
			XmlNode edition = doc.ImportNode(b.SerializeToXmlElement(), true);
			editionsNode.AppendChild(edition);
			edition.AppendChild(doc.CreateElement("Impressions"));
			
			Console.WriteLine();
			Console.WriteLine(doc.GetOuterXml());
		}
    }

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