问题
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