CSharp · Console
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/72348095/conversion-of-the-special-characters-while-adding-it-to-the-xml-innertext-in-c-s
public class TestClass
{
public static void Test()
{
// Construct your XmlDocument (not shown in the question)
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<Root></Root>");
var eqnPartElm = xmlDoc.CreateElement("inf");
xmlDoc.DocumentElement.AppendChild(eqnPartElm);
// Add some non-ASCII text (here – is an En Dash character).
eqnPartElm.InnerText = "–CO–OR";
// Output to XML and escape all non-ASCII characters.
var xml = xmlDoc.GetOuterXml(indent : true, 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);
}
Console.WriteLine(File.ReadAllText(fileName));
}
}
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 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;
}
}
}