all groups > dotnet xml > september 2005 >
You're in the

dotnet xml

group:

Writing formatted XML


Re: Writing formatted XML <www.fruitfruit.com>
9/27/2005 12:00:00 AM
dotnet xml: http://msmvps.com/coad/archive/2004/06/22/8692.aspx
Using XmlDocument.Save(string file) produces a file with nicely indented
elements. XmlDocument.OuterXml returns a string without any formatting. If
you want a nicely formatted string (to display to the user, write to
console, etc), without directly writing to a file, you must use the
XmlTextWriter.
using System.IO;
using System.Xml;

public static string FormatXML(XmlDocument doc)
{
// Create a stream buffer that can be read as a string
using (StringWriter sw = new StringWriter())

// Create a specialized writer for XML code
using (XmlTextWriter xtw = new XmlTextWriter(sw))
{
// Set the writer to use indented (hierarchical) elements
xtw.Formatting = System.Xml.Formatting.Indented;

// Write the XML document to the stream
doc.WriteTo(xtw);

// Return the stream as a string
return sw.ToString();
}
}

[quoted text, click to view]

Writing formatted XML Dan
9/27/2005 6:31:03 AM
How would I write an XmlDocument to a file so that each node is properly
indented and followed by a carriage return?

AddThis Social Bookmark Button