The following PrettyPrintXML method formats arbitrary XML text with indentation and line breaks in the correct places. If the XML is not well-formed, an exception will be thrown. It formats the XML text using the Formatting.Indented mode of the XmlTextWriter:
private static string PrettyPrintXML(string xmlText)
{
string prettyPrintedXML = null;
using (MemoryStream memoryStream = new MemoryStream())
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.Unicode))
{
XmlDocument xmlDocument = new XmlDocument();
// Load the XmlDocument with the XML.
xmlDocument.LoadXml(xmlText.Trim());
xmlTextWriter.Formatting = Formatting.Indented;
// Write the XML into a formatting XmlTextWriter
xmlDocument.WriteContentTo(xmlTextWriter);
xmlTextWriter.Flush();
memoryStream.Flush();
// Have to rewind the MemoryStream in order to read
// its contents.
memoryStream.Position = 0;
// Read MemoryStream contents into a StreamReader.
using (StreamReader streamReader = new StreamReader(memoryStream))
{
// Extract the text from the StreamReader.
prettyPrintedXML = streamReader.ReadToEnd();
}
}
return prettyPrintedXML;
}
I use it that method in my C# Programmable Calculator app to pretty-print XML text from the clipboard:
private static String GetClipboardText()
{
string result = "";
IDataObject iData = Clipboard.GetDataObject();
if (iData.GetDataPresent(DataFormats.Text))
{
result = (String) iData.GetData(DataFormats.Text);
}
return result;
}
[Button("Debugging", "Pretty-Print XML in Clipboard")]
public static void PrettyPrintXML()
{
string originalXML = GetClipboardText().Trim();
string prettyPrintedXML = null;
int startIndex = originalXML.IndexOf("<");
int stopIndex = originalXML.LastIndexOf("<");
if (startIndex >= 0 && stopIndex > 0)
{
originalXML = originalXML.Substring(startIndex, stopIndex - startIndex + 1);
try
{
prettyPrintedXML = PrettyPrintXML(originalXML);
}
catch (Exception)
{
}
TextLines textLines = new TextLines();
textLines.AddLine(prettyPrintedXML);
SetClipboardText(prettyPrintedXML);
iGUIUtils.DisplayTextLines("XML", textLines.Lines);
}
else
{
MessageBox.Show(originalXML, "Not Well-Formed XML", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
| Title | Date |
| Node.js + Express: How to Block Requests by User-Agent Headers | January 7, 2026 |
| Vault 3 is Now Available for Windows on ARM Machines! | December 13, 2025 |
| Vault 3: How to Include Outline Text in Exported Photos | October 26, 2025 |
| .NET Public-Key (Asymmetric) Cryptography Demo | July 20, 2025 |
| Raspberry Pi 3B+ Photo Frame | June 17, 2025 |
| EBTCalc (Android) Version 1.53 is now available | May 19, 2024 |
| Vault 3 Security Enhancements | October 24, 2023 |