[Fork] [Fork] [Fork] https://stackoverflow.com/questions/72348095/conversion-of-the-special-characters-while-adding-it-to-the-xml-innertext-in-c-s

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.IO;

using NUnit.Framework; //NUnit.Framework.AssertionException

//https://stackoverflow.com/questions/72898584/why-is-xmlwriter-failing-to-replace-characters-not-supported-by-the-current-enco

    public static class XmlSerializationHelper
    {
		public static string GetOuterXml(this XmlNode node, bool indent = false, Encoding encoding = null, bool omitXmlDeclaration = false)
		{
			if (node == null)
				return null;
			using var stream = new MemoryStream();
			node.Save(stream, indent : indent, encoding : encoding, omitXmlDeclaration : omitXmlDeclaration, closeOutput : false);
			stream.Position = 0;
			using var reader = new StreamReader(stream);
			return reader.ReadToEnd();
		}

		public static void Save(this XmlNode node, Stream stream, bool indent = false, Encoding encoding = null, bool omitXmlDeclaration = false, bool closeOutput = true) =>
			node.Save(stream, new XmlWriterSettings
					  {
						  Indent = indent,
						  Encoding = encoding,
						  OmitXmlDeclaration = omitXmlDeclaration,
						  CloseOutput = closeOutput,
					  });

		public static void Save(this XmlNode node, Stream stream, XmlWriterSettings settings)
		{
			using (var xmlWriter = XmlWriter.Create(stream, settings))
			{
				node.WriteTo(xmlWriter);
			}
		}
    }
				
    public class TestClass
    {
        public static void Test()
        {
			var xmlDoc = new XmlDocument();
			xmlDoc.LoadXml("<Root>ā€˜</Root>");

			// Output to XML and escape all non-ASCII characters.
			var xml = xmlDoc.GetOuterXml(encoding : Encoding.ASCII, omitXmlDeclaration : true);
			
			Console.WriteLine(xml);

			var fileName = "Question72348095.xml";
			
            using (var stream = new FileStream(fileName, FileMode.OpenOrCreate))
            {
				xmlDoc.Save(stream, indent : true, encoding : Encoding.ASCII, omitXmlDeclaration : true);
            }
			
			Console.WriteLine(File.ReadAllText(fileName));
		}
    }

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1}, {2})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
			Console.WriteLine();

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