Reputation: 2571
How can I format the contents of an XElement object?
I know that the output string is automatically formatted when calling .ToString(), but I want to add the whitespace nodes before converting the objects to string.
The intention is to format XML nodes in the model that is generated by the Microsoft.VisualStudio.XmlEditor classes.
Upvotes: 0
Views: 532
Reputation: 854
Add text as child element (stored as XText):
string xml = "<a><b>b</b></a>";
XElement xdoc = XElement.Parse(xml);
var b = xdoc.Element("b");
b.AddBeforeSelf(" ");
b.AddAfterSelf(new XText(" "));
b.Add(" ");
b.AddFirst(" ");
Console.WriteLine(xdoc.ToString(SaveOptions.DisableFormatting));
Example of universal formating (any xml):
string xml = "<a><b a=\"a\"><c><d>d</d></c></b><b a=\"a\"><c><d>d</d></c></b><e b=\"b\" a=\"a\"><f>f</f></e></a>";
XElement xdoc = XElement.Parse(xml);
Format(xdoc, 0);
Console.WriteLine(xdoc.ToString(SaveOptions.DisableFormatting));
static void Format(XElement x, int level)
{
foreach (var x1 in x.Elements())
Format(x1, level + 1);
if (level > 0)
{
x.AddBeforeSelf(Environment.NewLine + new string(' ', 2 * level));
if (x.Parent.LastNode == x)
{
string ending = Environment.NewLine;
if (level > 1)
ending += new string(' ', 2 * (level - 1));
x.AddAfterSelf(ending);
}
}
}
Upvotes: 2