Skip to content

Instantly share code, notes, and snippets.

@FilipDeVos
Last active December 21, 2015 06:58
Show Gist options
  • Save FilipDeVos/6267579 to your computer and use it in GitHub Desktop.
Save FilipDeVos/6267579 to your computer and use it in GitHub Desktop.
Extension method to output xml declaration with tostring
using System.IO;
using System.Text;
using System.Xml.Linq;
/// <summary>
/// Extension methods on the XDocument class.
/// </summary>
internal static class XDocumentExtensions
{
/// <summary>
/// The normal ToString does not return the Xml Declaration line.
/// This one allows you to specify if you want it or not.
/// </summary>
/// <param name="doc">The XDocument to return as a string</param>
/// <param name="includeXmlDeclaration">When true the Xml Declaration will be included.</param>
/// <returns>The string representation of the xml document encoded as UTF8 </returns>
public static string ToString(this XDocument doc, bool includeXmlDeclaration)
{
return ToString(doc, includeXmlDeclaration, Encoding.UTF8);
}
/// <summary>
/// The normal ToString does not return the Xml Declaration line. This one allows you to specify if you want it or not.
/// </summary>
/// <param name="doc">The XDocument to return as a string</param>
/// <param name="includeXmlDeclaration">When true the Xml Declaration will be included.</param>
/// <param name="encoding">The string encoding to use</param>
/// <returns>The string representation of the xml document</returns>
public static string ToString(this XDocument doc, bool includeXmlDeclaration, Encoding encoding)
{
if (!includeXmlDeclaration)
return doc.ToString();
using (var sw = new MemoryStream())
using (var strw = new StreamWriter(sw, encoding))
{
doc.Save(strw);
return encoding.GetString(sw.ToArray());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment