[Fork] [Fork] questions/46415814/remove-namespace-attribute-from-xml-node-in-serialized-value

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/46415814/remove-namespace-attribute-from-xml-node-in-serialized-value

    [XmlRoot("OutlTxt", Namespace = OutlineText.Namespace)]
    public class OutlineText : IXmlSerializable
    {
        public const string Namespace = "http://www.mynamespace/09262017";

        private string _value;

        // For debugging purposes.
        internal string InnerValue { get { return _value; } }

        static string EscapeTextValue(string text)
        {
            return Regex.Replace(text, @"[\a\b\f\n\r\t\v\\""'&<>]", m => string.Join(string.Empty, m.Value.Select(c => string.Format("&#x{0:X};", Convert.ToInt32(c))).ToArray()));
        }

        public OutlineText() // Needs to be public on dotnetfiddle for security reasons
        { }

        public OutlineText(string text)
        {
            _value = text;
        }

        #region IXmlSerializable Members

        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            _value = ((XElement)XNode.ReadFrom(reader)).Value;
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            var escapedValue = EscapeTextValue(_value);
            var nestedXml = string.Format("<p style=\"text-align:left;margin-top:0pt;margin-bottom:0pt;\"><span>{0}</span></p>", escapedValue);
            writer.WriteRaw(nestedXml);
        }

        #endregion
    }

    [XmlRoot("Container", Namespace = OutlineText.Namespace)]
    public class Container
    {
        public OutlineText [] Text { get; set; }

        public string ZZValue { get; set; }
    }

    class TestClass
    {
        public static void Test()
        {
            Test(@"SUBSTA SF6 CIRCUIT BKR CONC FDN ""C""");

            Test(@"");

            Test(@"<");

            Test(@">");
			
            TestContainer(@"SUBSTA SF6 CIRCUIT BKR CONC FDN ""C""");

            Console.WriteLine("\nDone.");
        }
		
        static void Test(string innerValue)
        {
            Console.WriteLine(string.Format("\nTesting {0} with input Value \"{1}\"", typeof(OutlineText), innerValue));

            var outlineText = new OutlineText(innerValue);

            var xml = outlineText.GetXml();

            Console.WriteLine(string.Format("\nSerialized {0}:", outlineText));
            Console.WriteLine(xml);

            var outlineText2 = xml.LoadFromXml<OutlineText>();
            var xml2 = outlineText2.GetXml();

            Console.WriteLine(string.Format("Re-serialized {0}:", outlineText2));
            Console.WriteLine(xml2);

            Assert.IsTrue(outlineText.InnerValue == outlineText2.InnerValue);
        }

        static void TestContainer(string innerValue)
        {
            Console.WriteLine(string.Format("\nTesting {0} with input Value \"{1}\"", typeof(Container), innerValue));

            var outlineText = new OutlineText(innerValue);
            var container = new Container { Text = new[] { outlineText }, ZZValue = "zz value" };

            var xml = container.GetXml();

            Console.WriteLine(string.Format("\nSerialized {0}:", outlineText));
            Console.WriteLine(xml);

            var container2 = xml.LoadFromXml<Container>();

            var xml2 = container2.GetXml();
            Console.WriteLine(string.Format("Re-serialized {0}:", container2));
            Console.WriteLine(xml2);

            Assert.IsTrue(container.ZZValue == container2.ZZValue);
            Assert.IsTrue(container.Text.Select(t => t.InnerValue).SequenceEqual(container2.Text.Select(t => t.InnerValue)));
        }
    }

    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 static class XmlSerializationHelper
    {
        public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
        {
            serial = serial ?? new XmlSerializer(typeof(T));
            T returnValue = default(T);
            using (StringReader reader = new StringReader(xmlString))
            {
                object result = serial.Deserialize(reader);
                if (result is T)
                {
                    returnValue = (T)result;
                }
            }
            return returnValue;
        }

        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 class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: " + Environment.Version);
			Console.WriteLine();

			TestClass.Test();
		}
	}
;