是什么让缩进的XML与XmlDocument的换行符最简单的方法是什么? [英] What is the simplest way to get indented XML with line breaks from XmlDocument?
问题描述
当我与的XmlDocument
构建XML从头开始,在 OuterXml
属性已有一切都很好地缩进与换行。但是,如果我叫 loadXML的
一些非常COM pressedXML(没有换行符或缩进),则输出 OuterXml
保持这种方式。所以......
When I build XML up from scratch with XmlDocument
, the OuterXml
property already has everything nicely indented with line breaks. However, if I call LoadXml
on some very "compressed" XML (no line breaks or indention) then the output of OuterXml
stays that way. So ...
什么是得到美化XML输出从的XmlDocument
?
What is the simplest way to get beautified XML output from an instance of XmlDocument
?
推荐答案
根据其他答案,我看着的XmlTextWriter
,并提出了以下辅助方法:
Based on the other answers, I looked into XmlTextWriter
and came up with the following helper method:
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();
}
这是一个有点更code不是我希望的,但它只是桃色。
It's a bit more code than I hoped for, but it works just peachy.
这篇关于是什么让缩进的XML与XmlDocument的换行符最简单的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!