Save xml or XmlNode string to text file indented format?

I have an xml line that is very long on one line. I would like to save the xml string to a text file in a good indentation format:

<root><app>myApp</app><logFile>myApp.log</logFile><SQLdb><connection>...</connection>...</root>

The format I prefer:

<root>
   <app>myApp</app>
   <logFile>myApp.log</logFile>
   <SQLdb>
      <connection>...</connection>
      ....
   </SQLdb>
</root>

What are .Net libraries for C # for?

+5
source share
2 answers

This will work for what you want to do ...

var samp = @"<root><app>myApp</app><logFile>myApp.log</logFile></root>";    
var xdoc = XDocument.Load(new StringReader(samp), LoadOptions.None);
xdoc.Save(@"c:\temp\myxml.xml", SaveOptions.None);

Same result with System.Xml namespace ...

var xdoc = new XmlDocument();
xdoc.LoadXml(samp);
xdoc.Save(@"c:\temp\myxml.xml");
+7
source

I assume that you do not mean that you have an instance of System.String with some XML in it, and I hope you do not create it using string manipulations.

, , , XmlWriter:

var sb = new StringBuilder();
var settings = new XmlWriterSettings {Indent = true};
using (var writer = XmlWriter.Create(sb, settings))
{
    // write your XML using the writer
}

// Indented results available in sb.ToString()
+3

All Articles