[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
    {
        public const string Namespace = "http://www.mynamespace/09262017";

        private string _value;

        [XmlAnyElement("TextOutlTxt", Namespace = OutlineText.Namespace)]
        public XElement Value
        {
            get
            {
                var escapedValue = EscapeTextValue(_value);

                var nestedXml = string.Format("<p xmlns=\"{0}\" style=\"text-align:left;margin-top:0pt;margin-bottom:0pt;\"><span>{1}</span></p>", Namespace, escapedValue);
                var outerXml = string.Format("<TextOutlTxt xmlns=\"{0}\">{1}</TextOutlTxt>", Namespace, nestedXml);

                var element = XElement.Parse(outerXml);

                //Remove redundant xmlns attributes
                element.DescendantsAndSelf().SelectMany(e => e.Attributes()).Where(a => a.IsNamespaceDeclaration && a.Value == Namespace).Remove();

                return element;
            }
            set
            {
                _value = value == null ? null : value.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()));
        }

        private OutlineText()
        { }

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


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

            Console.WriteLine("\nDone.");
		}
		
		static void Test(string innerValue)
		{
            Console.WriteLine("\nInput Value: ");
            Console.WriteLine(innerValue);

            var outlineText = new OutlineText(innerValue);

            var xml = outlineText.GetXml();

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

    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();
		}
	}
;