如何在c#中从XDocument创建缩进的XML字符串?

JC.*_*JC. 23 c# linq-to-xml

我有一个XDocument对象,ToString()方法返回XML而没有任何缩进.如何从包含缩进的XML创建字符串?

编辑:我问的是如何创建一个内存字符串而不是写出文件.

编辑:看起来我不小心在这里问了一个技巧问题... ToString()确实返回缩进的XML.

Joh*_*ers 24

XDocument doc = XDocument.Parse(xmlString);
string indented = doc.ToString();
Run Code Online (Sandbox Code Playgroud)

  • 这很好用.`XDocument.ToString()`默认格式为缩进.要获得未格式化的输出,您必须通过调用`.ToString(SaveOptions.DisableFormatting)来避开输出. (10认同)
  • 我实际上是在寻找禁用。谢谢@JoelMueller (2认同)

tom*_*ing 9

这里开始

XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");

// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter("data.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
Run Code Online (Sandbox Code Playgroud)

  • -1:问题是关于XDocument,而不是XmlDocument. (3认同)
  • @JC:使用 StringWriter 而不是 XmlTextWriter 构造函数中的文件名来获取字符串。 (2认同)
  • -1:不要使用 .NET 1.1 以后的 `new XmlTextWriter()` 或 `new XmlTextReader()`。使用“XmlWriter.Create()”或“XmlReader.Create()”。 (2认同)

小智 7

还有一种同样的汤的味道... ;-)

StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
Console.WriteLine(sw.ToString());
Run Code Online (Sandbox Code Playgroud)

编辑:感谢John Saunders.这是一个更适合在MSDN上创建XML Writer的版本.

using System;
using System.Text;
using System.Xml;
using System.Xml.Linq;

class Program
{
    static void Main(string[] args)
    {
        XDocument doc = new XDocument(
        new XComment("This is a comment"),
        new XElement("Root",
            new XElement("Child1", "data1"),
            new XElement("Child2", "data2")
            )
            );

        var builder = new StringBuilder();
        var settings = new XmlWriterSettings()
        {
            Indent = true
        };
        using (var writer = XmlWriter.Create(builder, settings))
        {
            doc.WriteTo(writer);
        }
        Console.WriteLine(builder.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 喜欢这个,但你的用途在哪里?! (3认同)

Doc*_*Max 6

要使用 XDocument(而不是 XmlDocument)创建字符串,您可以使用:

        XDocument doc = new XDocument(
            new XComment("This is a comment"),
            new XElement("Root",
                new XElement("Child1", "data1"),
                new XElement("Child2", "data2")
            )
        );

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        StringBuilder sb = new StringBuilder();
        using (XmlWriter writer = XmlTextWriter.Create(sb, settings)) {
            doc.WriteTo(writer);
            writer.Flush();
        }
        string outputXml = sb.ToString();
Run Code Online (Sandbox Code Playgroud)

编辑:更新为使用XmlWriter.CreateStringBuilder良好的形式(using)。

  • @JohnSaunders:再次感谢并再次更新。我怀疑我最初是想专注于基本行为,但草率的示例往往会在其他地方出现草率的代码。 (2认同)