当我从头开始构建XML时XmlDocument
,该OuterXml
属性已经通过换行符很好地缩进了所有内容.但是,如果我调用LoadXml
一些非常"压缩"的XML(没有换行或缩进),那么输出会OuterXml
保持这种状态.所以......
从一个实例中获取美化XML输出的最简单方法是XmlDocument
什么?
根据其他答案,我调查XmlTextWriter
并提出了以下帮助方法:
static public string Beautify(this XmlDocument doc) { StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace }; using (XmlWriter writer = XmlWriter.Create(sb, settings)) { doc.Save(writer); } return sb.ToString(); }
它的代码比我希望的要多一些,但它只是很有用.
根据Erika Ehrli的博客改编,应该这样做:
XmlDocument doc = new XmlDocument(); doc.LoadXml("- "); // Save the document to a file and auto-indent the output. using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) { writer.Formatting = Formatting.Indented; doc.Save(writer); }
wrench
如果您可以访问Linq,甚至更容易
try { RequestPane.Text = System.Xml.Linq.XElement.Parse(RequestPane.Text).ToString(); } catch (System.Xml.XmlException xex) { displayException("Problem with formating text in Request Pane: ", xex); }
较短的扩展方法版本
public static string ToIndentedString( this XmlDocument doc ) { var stringWriter = new StringWriter(new StringBuilder()); var xmlTextWriter = new XmlTextWriter(stringWriter) {Formatting = Formatting.Indented}; doc.Save( xmlTextWriter ); return stringWriter.ToString(); }
如果为XmlDocument
已经包含XmlProcessingInstruction
子节点的方法调用上述Beautify方法,则抛出以下异常:
无法编写XML声明.WriteStartDocument方法已经写好了.
这是我原来的修改版本摆脱异常:
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(); } }
它现在适用于我,可能你需要扫描节点的所有子XmlProcessingInstruction
节点,而不仅仅是第一个节点?
2015年4月更新:
由于我有另一个编码错误的情况,我搜索了如何在没有BOM的情况下强制执行UTF-8.我找到了这篇博客文章并基于它创建了一个函数:
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; } }
XmlTextWriter xw = new XmlTextWriter(writer); xw.Formatting = Formatting.Indented;
public static string FormatXml(string xml) { try { var doc = XDocument.Parse(xml); return doc.ToString(); } catch (Exception) { return xml; } }