Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If the above Beautify method is being called for an <code>XmlDocument</code> that already contains an <code>XmlProcessingInstruction</code> child node the following exception is thrown:</p> <blockquote> <p>Cannot write XML declaration. WriteStartDocument method has already written it.</p> </blockquote> <p>This is my modified version of the original one to get rid of the exception:</p> <pre><code>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(); } } </code></pre> <p>It works for me now, probably you would need to scan all child nodes for the <code>XmlProcessingInstruction</code> node, not just the first one?</p> <hr> <p><strong>Update April 2015:</strong></p> <p>Since I had another case where the encoding was wrong, I searched for how to enforce UTF-8 without BOM. I found <a href="http://www.timvw.be/2007/01/08/generating-utf-8-with-systemxmlxmlwriter/" rel="noreferrer">this blog post</a> and created a function based on it:</p> <pre><code>private static string beautify(string xml) { var doc = new XmlDocument(); doc.LoadXml(xml); var settings = new XmlWriterSettings { Indent = true, IndentChars = "\t", NewLineChars = Environment.NewLine, NewLineHandling = NewLineHandling.Replace, Encoding = new UTF8Encoding(false) }; using (var ms = new MemoryStream()) using (var writer = XmlWriter.Create(ms, settings)) { doc.Save(writer); var xmlString = Encoding.UTF8.GetString(ms.ToArray()); return xmlString; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload