[questions/48659674/how-to-insert-a-node-in-a-large-document-using-xmlserializer

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;

    // https://stackoverflow.com/questions/48659674/how-to-insert-a-node-in-a-large-document-using-xmlserializer
    [XmlRoot("Car", Namespace = "http://MyNamespace")]
    [XmlType("Car", Namespace = "http://MyNamespace")]
    public class Car
    {
        [XmlAttribute]
        public string make { get; set; }
    }

    class TestClass
    {
        public static void Test()
        {
            TestWriteMcve();
        }

        static string XmlContent = @"
    <RootNode xmlns=""http://MyNamespace"">
        <Cars>
        <Car make=""Volkswagen"" />
        <Car make=""Ford"" />
        <Car make=""Opel"" />
        </Cars>
    </RootNode>";

        static string XmlContent2 = @"
    <RootNode xmlns:ns=""http://MyNamespace"">
        <ns:Cars>
        <ns:Car make=""Volkswagen"" />
        <ns:Car make=""Ford"" />
        <ns:Car make=""Opel"" />
        </ns:Cars>
    </RootNode>";

        private static void TestWriteMcve()
        {
            // Check what happens when the http://MyNamespace namespace is the default namespace
            TestWriteMcve(XmlContent);
            Console.WriteLine();
            // Check what happens when the http://MyNamespace namespace is a named namespace
            TestWriteMcve(XmlContent2);
        }


        private static void TestWriteMcve(string content)
        {
            var doc = new XmlDocument();
            doc.LoadXml(content);
            var nsMgr = new XmlNamespaceManager(doc.NameTable);
            nsMgr.AddNamespace("myns", "http://MyNamespace");

            var newCar = new Car { make = "BMW" };

            var node = doc.DocumentElement.SelectSingleNode("myns:Cars/myns:Car[@make='Ford']", nsMgr);

            node = TestReplace(doc, node, newCar);

            // Check that null works
            node = TestReplace(doc, node, null);

            node = TestReplace(doc, node, newCar);
        }

        private static XmlNode TestReplace(XmlDocument doc, XmlNode node, Car newCar)
        {
            node = node.ReplaceWithSerializationOf(newCar);
            var parent = node.ParentNode;

            Console.WriteLine("Replacement: ");
            Console.WriteLine(node.OuterXml);
            Console.WriteLine("Entire document: ");
            Console.WriteLine(doc.GetOuterXml());

            return node;
        }
    }

    public static class XmlNodeExtensions
    {
        public static XmlNode ReplaceWithSerializationOf<T>(this XmlNode node, T replacement)
        {
            if (node == null)
                throw new ArgumentNullException();
            var parent = node.ParentNode;
            var serializer = new XmlSerializer(replacement == null ? typeof(T) : replacement.GetType());

            using (var writer = node.CreateNavigator().InsertAfter())
            {
                // WriteWhitespace needed to avoid error "WriteStartDocument cannot
                // be called on writers created with ConformanceLevel.Fragment."
                writer.WriteWhitespace("");

                // Set up an appropriate initial namespace.
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add(node.GetNamespaceOfPrefix(node.NamespaceURI), node.NamespaceURI);

                // Serialize
                serializer.Serialize(writer, replacement, ns);
            }

            var nextNode = node.NextSibling;
            parent.RemoveChild(node);
            return nextNode;
        }
    }

    public static class XmlSerializationHelper
    {
		public static string GetOuterXml(this XmlNode node, bool indent = true)
		{
			if (node == null)
				return null;
			using (var textWriter = new StringWriter())
			{
				var settings = new XmlWriterSettings
				{
					Indent = indent,
					OmitXmlDeclaration = true,
				};
				using (var xmlWriter = XmlWriter.Create(textWriter, settings))
				{
					node.WriteTo(xmlWriter);
				}
				return textWriter.ToString();
			}
		}
    }
				
    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 class Program
	{
		public static void Main()
		{
			Console.WriteLine("Roslyn 2.0 Compiler; Environment version: " + Environment.Version);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Uncaught exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;