Skip to content

Instantly share code, notes, and snippets.

@LSTANCZYK
Last active November 21, 2017 20:26
Show Gist options
  • Save LSTANCZYK/f5154424af35462d5f0304c9f12e62ab to your computer and use it in GitHub Desktop.
Save LSTANCZYK/f5154424af35462d5f0304c9f12e62ab to your computer and use it in GitHub Desktop.
Formats XML string with indentations for easier reading
private static String FormatXml(string xml)
{
String Result = "";
MemoryStream mStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
XmlDocument document = new XmlDocument();
try
{
// Load the XmlDocument with the XML.
document.LoadXml(xml);
writer.Formatting = Formatting.Indented;
// Write the XML into a formatting XmlTextWriter
document.WriteContentTo(writer);
writer.Flush();
mStream.Flush();
// Have to rewind the MemoryStream in order to read
// its contents.
mStream.Position = 0;
// Read MemoryStream contents into a StreamReader.
StreamReader sReader = new StreamReader(mStream);
// Extract the text from the StreamReader.
String formattedXml = sReader.ReadToEnd();
Result = formattedXml;
}
catch (XmlException)
{
return xml;
}
mStream.Close();
writer.Close();
return Result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment