If the above Beautify method is being called for an XmlDocument that already contains an XmlProcessingInstruction child node the following exception is thrown:
  Cannot write XML declaration.
  WriteStartDocument method has already
  written it.
This is my modified version of the original one to get rid of the exception:
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();
    }
}
It works for me now, probably you would need to scan all child nodes for the XmlProcessingInstruction node, not just the first one?