Questions40388472 C# XML Serialize without a wrapper

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;


    public class varString
    {
        [XmlText]
        public string Value;
        public string KeyWord;
        public static implicit operator string(varString v)
        {
            return v == null ? null : (string)v.Value;
        }
    }
						
	public class Program
	{
		public static void Main()
		{
			var test1 = new varString { KeyWord = "key word", Value = "my value" };
			Console.WriteLine(test1.GetXml(true));
			var test2 = new varString { Value = "my value" };
			Console.WriteLine(test2.GetXml(true));
		}
	}

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