0

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.

TWT
  • 2,511
  • 1
  • 23
  • 37

1 Answers1

2

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);
            }
        }
    }
Alexey Obukhov
  • 834
  • 9
  • 18
  • I want to add the whitespace in the XElement objects itself, instead of the string output. – TWT Mar 25 '16 at 14:41
  • xelement does not store whitespaces. it is not a string. it stores content of tag (inside <>...>), content of attributes, but not a content before or after <>. please, do not give negative reputation. thanks ) – Alexey Obukhov Mar 25 '16 at 14:46
  • just press F12 on xelement and look declaration. It has Name, Value properties, Attributes() method. There is no Whitespace property. – Alexey Obukhov Mar 25 '16 at 14:51
  • I know, but an XElement can have XText children objects, with whitespace as content. – TWT Mar 30 '16 at 10:14
  • you are right. xelement can has any xnode in children elements. updated answer. – Alexey Obukhov Mar 30 '16 at 10:52
  • Thanks for the update. But how can an XElement be formatted when it doesn't have fixed child content? – TWT Mar 30 '16 at 14:41
  • added formating function to example. writes newlines and spaces to each xelement. analog of xdoc.ToString(SaveOptions.None) – Alexey Obukhov Mar 30 '16 at 15:31