当我使用XmlDocument
从头开始构建XML时,OuterXml
属性已经通过换行符很好地缩进了所有内容。但是,如果我在一些非常“压缩”的XML上调用LoadXml
(没有换行或缩进),那么OuterXml
的输出就会保持这种状态。所以...
从XmlDocument
的实例获取美化XML输出的最简单方法是什么?
答案 0 :(得分:198)
基于其他答案,我调查了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();
}
它的代码比我希望的要多一些,但它只是很有用。
答案 1 :(得分:44)
改编自Erika Ehrli's博客,应该这样做:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// 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);
}
答案 2 :(得分:39)
如果您可以访问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);
}
答案 3 :(得分:16)
较短的扩展方法版本
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();
}
答案 4 :(得分:10)
如果为已经包含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。我找到this blog post并根据它创建了一个函数:
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;
}
}
答案 5 :(得分:7)
XmlTextWriter xw = new XmlTextWriter(writer);
xw.Formatting = Formatting.Indented;
答案 6 :(得分:4)
public static string FormatXml(string xml)
{
try
{
var doc = XDocument.Parse(xml);
return doc.ToString();
}
catch (Exception)
{
return xml;
}
}
答案 7 :(得分:2)
一种简单的方法是使用:
writer.WriteRaw(space_char);
就像这个示例代码一样,这段代码是我用来创建类似于使用XMLWriter的结构的树视图的代码:
private void generateXML(string filename)
{
using (XmlWriter writer = XmlWriter.Create(filename))
{
writer.WriteStartDocument();
//new line
writer.WriteRaw("\n");
writer.WriteStartElement("treeitems");
//new line
writer.WriteRaw("\n");
foreach (RootItem root in roots)
{
//indent
writer.WriteRaw("\t");
writer.WriteStartElement("treeitem");
writer.WriteAttributeString("name", root.name);
writer.WriteAttributeString("uri", root.uri);
writer.WriteAttributeString("fontsize", root.fontsize);
writer.WriteAttributeString("icon", root.icon);
if (root.children.Count != 0)
{
foreach (ChildItem child in children)
{
//indent
writer.WriteRaw("\t");
writer.WriteStartElement("treeitem");
writer.WriteAttributeString("name", child.name);
writer.WriteAttributeString("uri", child.uri);
writer.WriteAttributeString("fontsize", child.fontsize);
writer.WriteAttributeString("icon", child.icon);
writer.WriteEndElement();
//new line
writer.WriteRaw("\n");
}
}
writer.WriteEndElement();
//new line
writer.WriteRaw("\n");
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
这样您可以按照常用的方式添加制表符或换行符,即\ t或\ n
答案 8 :(得分:1)
在实施此处发布的建议时,我遇到了文本编码问题。似乎XmlWriterSettings
的编码被忽略,并且总是被流的编码覆盖。使用StringBuilder
时,这始终是C#内部使用的文本编码,即UTF-16。
所以这是一个支持其他编码的版本。
重要说明:如果XMLDocument
对象在加载文档时启用了preserveWhitespace
属性,则会完全忽略格式设置。这让我感到困惑了一段时间,所以一定不要启用它。
我的最终代码:
public static void SaveFormattedXml(XmlDocument doc, String outputPath, Encoding encoding)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
settings.NewLineChars = "\r\n";
settings.NewLineHandling = NewLineHandling.Replace;
using (MemoryStream memstream = new MemoryStream())
using (StreamWriter sr = new StreamWriter(memstream, encoding))
using (XmlWriter writer = XmlWriter.Create(sr, settings))
using (FileStream fileWriter = new FileStream(outputPath, FileMode.Create))
{
if (doc.ChildNodes.Count > 0 && doc.ChildNodes[0] is XmlProcessingInstruction)
doc.RemoveChild(doc.ChildNodes[0]);
// save xml to XmlWriter made on encoding-specified text writer
doc.Save(writer);
// Flush the streams (not sure if this is really needed for pure mem operations)
writer.Flush();
// Write the underlying stream of the XmlWriter to file.
fileWriter.Write(memstream.GetBuffer(), 0, (Int32)memstream.Length);
}
}
这将使用给定的文本编码将格式化的xml保存到磁盘。
答案 9 :(得分:1)
如果你有一串XML,而不是可以使用的文档,你可以这样做:
var xmlString = "<xml>...</xml>"; // Your original XML string that needs indenting.
xmlString = this.PrettifyXml(xmlString);
private string PrettifyXml(string xmlString)
{
var prettyXmlString = new StringBuilder();
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
var xmlSettings = new XmlWriterSettings()
{
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(prettyXmlString, xmlSettings))
{
xmlDoc.Save(writer);
}
return prettyXmlString.ToString();
}
答案 10 :(得分:1)
基于公认答案的更简化方法:
static public string Beautify(this XmlDocument doc) {
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
doc.Save(writer);
}
return sb.ToString();
}
无需设置新行。缩进字符也有默认的两个空格,所以我更喜欢不设置它。
答案 11 :(得分:0)
using System;
using System.Xml;
using System.Xml.Linq;
class Program
{
static void Main()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Customers.xml");
/* another function of XDocument.Parse() is formatting XML code which gived as string: */
Console.WriteLine(XDocument.Parse(xmlDoc.InnerXml));
}
}