Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

xml

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?

like image 616
David.Chu.ca Avatar asked May 03 '09 02:05

David.Chu.ca


People also ask

What is XmlNode in C#?

XmlNode is the base class in the . NET implementation of the DOM. It supports XPath selections and provides editing capabilities. The XmlDocument class extends XmlNode and represents an XML document. You can use XmlDocument to load and save XML data.

How to save data in XML file in c# windows application?

One simple way to do this would be to create . NET classes that you put the data in and then use XmlSerializer to serialize the data to a file and then later deserialize back into an instance of the class and re-populate the form. AS an example, if you have a form with customer data.


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");
like image 83
JP Alioto Avatar answered Oct 02 '22 08:10

JP Alioto


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()
like image 45
John Saunders Avatar answered Oct 02 '22 08:10

John Saunders