Question36745144 XmlType to override property names

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.Xml.Linq;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Runtime.Serialization;
using System.ComponentModel;
					

    [XmlType("Outer_X")]
    public class Outer
    {
        public Outer()
        {
            this.InnerItem = new Inner();
        }

        [XmlIgnore]
        public Inner InnerItem { get; set; }

        [XmlElement(typeof(Inner))]
        [XmlElement(typeof(object))]

		[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]

        public object InnerItemXmlProxy
        {
            get
            {
                return InnerItem;
            }
            set
            {
                InnerItem = (Inner)value;
            }
        }
    }

    [XmlType("Inner_X")]
    public class Inner
    {
    }

					
	public class Program
	{
		public static void Main()
		{
            var outer = new Outer { InnerItem = new Inner() };
            var xml = outer.GetXml();
            Console.WriteLine("Serialized XML:");
            Console.WriteLine(xml);
            var outer2 = xml.LoadFromXML<Outer>();
            var xml2 = outer2.GetXml();
            Console.WriteLine("Re-serialized XML:");
            Console.WriteLine(xml2);		
		}
	}

    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, 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, IndentChars = "    " }; // For cosmetic purposes.
                using (var xmlWriter = XmlWriter.Create(textWriter, settings))
                    new XmlSerializer(obj.GetType()).Serialize(xmlWriter, obj, ns);
                return textWriter.ToString();
            }
        }
    }

;