using System.Collections.Generic;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
public class CustomFormattingXmlTextWriter : XmlTextWriter
readonly Stack<Formatting> stack = new Stack<Formatting>();
public CustomFormattingXmlTextWriter(TextWriter writer, int indentDepth) : base(writer)
this.Formatting = Formatting.Indented;
this.IndentDepth = indentDepth;
void OnElementStarted(string localName, string ns)
if (stack.Count == IndentDepth+1)
Formatting = Formatting.None;
public override void WriteStartElement(string prefix, string localName, string ns)
base.WriteStartElement(prefix, localName, ns);
OnElementStarted(localName, ns);
public override void WriteEndElement()
public override void WriteFullEndElement()
public static partial class XNodeExtensions
public static void SaveWithCustomFormatting(this XDocument doc, string filename, int indentDepth)
using (var textWriter = new StreamWriter(filename))
using (var writer = new CustomFormattingXmlTextWriter(textWriter, indentDepth))
public static void Test()
var fileName = "Question57287775.xml";
var myDoc = new XDocument(new XElement("ROOTELEMENT",
new XElement("CHILDELEMENT",
new XElement("INFO1", "Test a 1"),
new XElement("INFO2", "Test a 2")),
new XElement("CHILDELEMENT",
new XElement("INFO1", "Test b 1"),
new XElement("INFO2", "Test b 2")),
new XElement("CHILDELEMENT")
myDoc.SaveWithCustomFormatting(fileName, 1);
Console.WriteLine(File.ReadAllText(fileName));
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];