David.Chu.ca
David.Chu.ca

Reputation: 38654

Save xml string or XmlNode to text file in indent format?

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?

Upvotes: 5

Views: 10542

Answers (3)

Antonio Rodr&#237;guez
Antonio Rodr&#237;guez

Reputation: 1126

Just another option:

using System.Xml.Linq;


public string IndentXmlString(string xml)
{
    XDocument doc = XDocument.Parse(xml);
    return doc.ToString();
}

Upvotes: 0

JP Alioto
JP Alioto

Reputation: 45117

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");

Upvotes: 7

John Saunders
John Saunders

Reputation: 161783

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()

Upvotes: 3

Related Questions