Spacing out output with Linq to Xml

本秂侑毒 提交于 2019-12-12 04:06:28

问题


How is it possible to force extra spacing between some nodes using Linq to Xml? I am looking to output the following:

<root>

    <group>
        <leaf />
    </group>

    <group>
        <leaf />
    </group>

</root>

By adding Empty XText, it only destroys the formatting.

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());

resulting in

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

回答1:


This is a solution but it´s not beautiful...

Change XText to XComment and do something like this...

 
    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);
    }

Edit: Fogott to escape lesser than ...




回答2:


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



回答3:


Pass an XmlTextWriter (with Formatting set to Formatting.Indented) to root.WriteTo().

For example:

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


来源:https://stackoverflow.com/questions/1950019/spacing-out-output-with-linq-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!