questions/42953870/xml-changes-after-serialization

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/42953870/xml-changes-after-serialization

    public partial class Message
    {
        [XmlNamespaceDeclarations]
        public XmlSerializerNamespaces XmlFileNamespaces { get; set; }

        /// <summary>
        /// returns a XmlSerializerNamespaces to use when serializing a Message as the root XML object.
        /// If Message was previously deserialized from XML, the actual namespaces observed will be returned.
        /// Otherwise, a default will be returned that suppresses output of the xmlns:xsi and xmlns:xsd namespace attributes.
        /// </summary>
        [XmlIgnore]
        public XmlSerializerNamespaces XmlRootNamespaces
        {
            get
            {
                if (XmlFileNamespaces != null)
                    return XmlFileNamespaces;
                var xmlNamespaces = new XmlSerializerNamespaces();
                xmlNamespaces.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
                // xmlNamespaces.Add("ns", "http://example.com"); // Or, if you prefer, add this namespace as well as disabling xmlns:xsi and xmlns:xsd.
                return xmlNamespaces;
            }
        }
    }

    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://example.com")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://example.com", IsNullable = false)]
    public partial class Message
    {

        private Header headerField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Namespace = "")]
        public Header Header
        {
            get
            {
                return this.headerField;
            }
            set
            {
                this.headerField = value;
            }
        }
    }

    public static class XmlSerializationHelper
    {
        public static T LoadFromXml<T>(this string xmlString)
        {
            using (StringReader reader = new StringReader(xmlString))
            {
                return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
            }
        }

        public static string GetXml<T>(this T obj, XmlSerializerNamespaces ns)
        {
            using (var textWriter = new Utf8StringWriter())
            {
                var settings = new XmlWriterSettings() { Indent = true }; // For cosmetic purposes.
                using (var xmlWriter = XmlWriter.Create(textWriter, settings))
                    new XmlSerializer(obj.GetType()).Serialize(xmlWriter, obj, ns);
                return textWriter.ToString();
            }
        }
    }

    // http://stackoverflow.com/questions/3862063/serializing-an-object-as-utf-8-xml-in-net
    public class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding
        {
            get { return Encoding.UTF8; }
        }
    }

    class TestClass
    {
        static string GetXml()
        {
            var xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<ns:Message xmlns:ns=""http://example.com"">
  <Header version=""1.0"">
    <Sender>3015207400109</Sender>
    <Receiver>8711200999903</Receiver>
    <MessageID>000D2613F64AC021ED783C084735EC78E53</MessageID>
    <CreationDateTime>2017-03-21T08:00:47Z</CreationDateTime>
  </Header>
</ns:Message>";
            return xml;
        }

        public static void Test()
        {
            var xml = GetXml();

            Console.WriteLine("\nInitial XML: ");
            Console.WriteLine(xml);

            var message = xml.LoadFromXml<Message>();

            var reserializedXml = message.GetXml(message.XmlRootNamespaces);

            Console.WriteLine("\nDeserialized and re-serialized XML: ");
            Console.WriteLine(reserializedXml);

            var message2 = new Message { Header = message.Header };

            var freshXml = message2.GetXml(message2.XmlRootNamespaces);

            Console.WriteLine("\nSerialized XML from a newly allocated Message instance: ");
            Console.WriteLine(freshXml);
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Header
    {
        private ulong senderField;

        private ulong receiverField;

        private string messageIDField;

        private System.DateTime creationDateTimeField;

        private decimal versionField;

        /// <remarks/>
        public ulong Sender
        {
            get
            {
                return this.senderField;
            }
            set
            {
                this.senderField = value;
            }
        }

        /// <remarks/>
        public ulong Receiver
        {
            get
            {
                return this.receiverField;
            }
            set
            {
                this.receiverField = value;
            }
        }

        /// <remarks/>
        public string MessageID
        {
            get
            {
                return this.messageIDField;
            }
            set
            {
                this.messageIDField = value;
            }
        }

        /// <remarks/>
        public System.DateTime CreationDateTime
        {
            get
            {
                return this.creationDateTimeField;
            }
            set
            {
                this.creationDateTimeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public decimal version
        {
            get
            {
                return this.versionField;
            }
            set
            {
                this.versionField = value;
            }
        }
    }

					
	public class Program
	{
		public static void Main()
		{
			TestClass.Test();
		}
	}
;