tags:

views:

420

answers:

2

I have an xml string which is very long in one line. I would like to save the xml string to a text file in a nice indent 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 available for C# to do it?

A: 

I'm going to assume you don't mean that you have a System.String instance with some XML in it, and I'm going to hope you don't create it via string manipulation.

That said, all you have to do is set the proper settings when you create your 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()
John Saunders
+2  A: 

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");
JP Alioto
where is the XDocument, I mean namespace?
David.Chu.ca
System.Xml.Linq, but you can do basically the same thing with the XmlDocument class.
JP Alioto