使用Linq将输出间隔到Xml

时间:2009-12-23 00:15:07

标签: xml linq linq-to-xml

如何使用Linq到Xml强制某些节点之间的额外间距?我希望输出以下内容:

<root>

    <group>
        <leaf />
    </group>

    <group>
        <leaf />
    </group>

</root>

通过添加Empty XText,它只会破坏格式化。

var root =
    new XElement("root",
        new XText(""),
        new XElement("group",
            new XElement("leaf")),
        new XText(""),
        new XElement("group",
            new XElement("leaf")),
        new XText(""));

Console.WriteLine(root.ToString());

导致

<root><group><child /></group><group><child /></group></root>

3 个答案:

答案 0 :(得分:1)

using (var writer = XmlWriter.Create(
    Console.Out,
    new XmlWriterSettings { Indent = true })
{
    root.WriteTo(writer);
}

答案 1 :(得分:1)

这是一个解决方案,但它不漂亮......

将XText更改为XComment并执行类似的操作......

 
    var root =
        new XElement("root",
            new XComment(""),
            new XElement("group",
                new XElement("leaf")),
            new XComment(""),
            new XElement("group",
                new XElement("leaf")),
            new XComment(""));

    Console.WriteLine(XElementToText(root));


    private string XElementToText(XElement element)
    {
        var sb = new StringBuilder();
        using (var writer = XmlWriter.Create(sb, 
            new XmlWriterSettings {Indent = true}))
        {
            element.WriteTo(writer);
        }
        return sb.ToString().Replace("<!---->", string.Empty);
    }

编辑:Fogott逃脱...... ...

答案 2 :(得分:0)

XmlTextWriterFormatting设置为Formatting.Indented)传递给root.WriteTo()

例如:

using(var writer = new XmlTextWriter(Console.Out));
{
    writer.Formatting = Formatting.Indented;
    root.WriteTo(writer);
}