111

当我从头开始构建 XML 时XmlDocument,该OuterXml属性已经将所有内容都很好地缩进了换行符。但是,如果我调用LoadXml一些非常“压缩”的 XML(没有换行符或缩进),那么输出就会OuterXml保持这种状态。所以 ...

从 的实例获取美化 XML 输出的最简单方法是XmlDocument什么?

4

11 回答 11

221

根据其他答案,我研究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();
}

它的代码比我希望的要多一些,但它的工作原理很简单。

于 2008-10-15T03:01:29.287 回答
51

改编自Erika Ehrli 的博客,应该这样做:

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);
}
于 2008-10-15T02:28:32.440 回答
41

如果您可以访问 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);
}
于 2012-07-20T15:49:09.617 回答
17

更短的扩展方法版本

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();
}
于 2010-10-16T03:11:45.203 回答
14

XmlDocument如果为已经包含子节点的节点调用上述 Beautify 方法,XmlProcessingInstruction则会引发以下异常:

无法编写 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;
    }
}
于 2009-09-13T07:14:05.070 回答
7
XmlTextWriter xw = new XmlTextWriter(writer);
xw.Formatting = Formatting.Indented;
于 2008-10-15T02:28:53.703 回答
6
    public static string FormatXml(string xml)
    {
        try
        {
            var doc = XDocument.Parse(xml);
            return doc.ToString();
        }
        catch (Exception)
        {
            return xml;
        }
    }
于 2014-11-17T00:39:09.143 回答
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

于 2012-07-09T13:30:38.170 回答
2

在实施此处发布的建议时,我遇到了文本编码问题。似乎 的编码XmlWriterSettings被忽略了,并且总是被流的编码覆盖。使用 a 时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 保存到磁盘。

于 2013-05-13T14:27:24.690 回答
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();
}
于 2014-07-09T16:52:13.110 回答
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(); 
}

不需要设置新行。缩进字符也有默认的两个空格,所以我也不想设置它。

于 2017-08-31T13:56:55.263 回答