Last active
November 21, 2017 20:26
-
-
Save LSTANCZYK/f5154424af35462d5f0304c9f12e62ab to your computer and use it in GitHub Desktop.
Formats XML string with indentations for easier reading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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