using System.Collections.Generic;
using System.Xml.Serialization;
public static class XmlSerializationHelper
public static string GetOuterXml(this XmlNode node, bool indent = false, Encoding encoding = null, bool omitXmlDeclaration = false)
using var stream = new MemoryStream();
node.Save(stream, indent : indent, encoding : encoding, omitXmlDeclaration : omitXmlDeclaration, closeOutput : false);
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
OmitXmlDeclaration = omitXmlDeclaration,
CloseOutput = closeOutput,
public static void Save(this XmlNode node, Stream stream, XmlWriterSettings settings)
using (var xmlWriter = XmlWriter.Create(stream, settings))
public static void Test()
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<Root><!--‘--></Root>");
var xml = xmlDoc.GetOuterXml(encoding : Encoding.ASCII, omitXmlDeclaration : true);
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 static void Main()
Console.WriteLine("Environment version: {0} ({1}, {2})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("Failed with unhandled exception: ");