www.softwareriviera.com
Software Code
    New Code     Most Interesting     Don't Miss     Our picks  
C# - section

View Article
Get indented XML output from an instance of XmlDocument
How do you get indented XML output from an instance of XmlDocument? The article below shows how to get indented XML output from from an instance of XmlDocument.
Did you wonder how you can get indented XML output from an instance of XmlDocument?

Please see below four snippets of code helping you to accomplish this.

Version 1:
static public string CreateIndendedXml(XmlDocument doc)
{
StringBuilder stringBuilder = new StringBuilder();

XmlWriterSettings xmlSettings = new XmlWriterSettings();
xmlSettings.Indent = true;
xmlSettings.IndentChars = " ";
xmlSettings.NewLineChars = "\r\n";
xmlSettings.NewLineHandling = NewLineHandling.Replace;

using (XmlWriter writer = XmlWriter.Create(stringBuilder, xmlSettings))
{
doc.Save( writer );
}

return stringBuilder.ToString();
}




Version 2:
XmlDocument doc = new XmlDocument();

doc.LoadXml("<item><name>wrench</name></item>");

// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter("data.xml",null);
writer.Formatting = Formatting.Indented;

doc.Save(writer);




Version 3:
public static string ToIndentedString( this XmlDocument doc )
{
var stringWriter = new StringWriter(new StringBuilder());
var xmlTextWriter = new XmlTextWriter(stringWriter) {Formatting = Formatting.Indented};
doc.Save( xmlTextWriter );
return stringWriter.ToString();
}




Version 4:
private static string beautify(
XmlDocument doc)
{
var sb = new StringBuilder();
var settings =
new XmlWriterSettings
{
Indent = true,
IndentChars = @" ",
NewLineChars = Environment.NewLine,
NewLineHandling = NewLineHandling.Replace,
};

using (var writer = XmlWriter.Create(sb, settings))
{
if (doc.ChildNodes[0] is XmlProcessingInstruction)
{
doc.RemoveChild(doc.ChildNodes[0]);
}

doc.Save(writer);
return sb.ToString();
}
}
Date: 2012-6-3    Written by: Admin A
     See all articles in this section
Copyright © 2007-2009 SoftwareRiviera.com. All rights reserved.  | Terms of use | Disclaimer | Privacy Policy |