deep copy an object using XmlSerialization - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

deep copy an object using XmlSerialization

Demo Code

// FreeBSD License
using System.Xml.Serialization;
using System.Xml;
using System.Text;
using System.Linq;
using System.IO;/*  w w w  .ja va2 s  . c  o m*/
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// deep copy an object using XmlSerialization
        /// </summary>
        /// <param name="elementName">name of surrounding element when writing the object</param>
        /// <param name="source">object to copy</param>
        /// <param name="destination">new blank element to copy into</param>
        public static void CloneUsingXmlSerialization(string elementName, IXmlSerializable source, IXmlSerializable destination)
        {
            XmlWriterSettings writeSettings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                ConformanceLevel = ConformanceLevel.Fragment,
                CloseOutput = false,
                Encoding = Encoding.UTF8
            };

            MemoryStream memoryStream = new MemoryStream();
            var xmlWriter = XmlWriter.Create(memoryStream, writeSettings);

            // simulate the behaviour of XmlSerialisation
            xmlWriter.WriteStartElement(elementName);
            source.WriteXml(xmlWriter);
            xmlWriter.WriteEndElement();

            xmlWriter.Flush();
            memoryStream.Position = 0;

            XmlReaderSettings readSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
            var reader = XmlReader.Create(memoryStream, readSettings);

            destination.ReadXml(reader);
        }
}

Related Tutorials