Yogesh
Yogesh

Reputation: 14608

Xml InnerXml indentation issue

I have a XmlDocument like this:

<Root>
  <Settings>
    <PresentationSettings>
    </PresentationSettings>
  </Settings>
</Root>

When I set the InnerXml of <PresentationSettings> with this text...

<Desktop>
  <WidgetElements>
    <WidgetElement Name="1">
    </WidgetElement>
    <WidgetElement Name="2">
    </WidgetElement>
  </WidgetElements>
</Desktop>

..., the output file is saved like this:

<Root>
  <Settings>
    <PresentationSettings>
      <Desktop>
  <WidgetElements>
    <WidgetElement Name="1">
    </WidgetElement>
    <WidgetElement Name="2">
    </WidgetElement>
  </WidgetElements>
</Desktop>
    </PresentationSettings>
  </Settings>
</Root>

It seems that the root of the InnerXml (i.e. <Desktop>) is starting from the right indented column, but rest of the InnerXml preserves it`s original indentation. I tried a lot of methods, but all of them are giving the exact same output. The methods I tried were:

Can anybody point me in the write direction? What am I doing wrong?

Upvotes: 3

Views: 1380

Answers (1)

Chuck Savage
Chuck Savage

Reputation: 11955

You should use XDocument or XElement, XmlDocument is .Net 2.0 aka antiquated.

Instead write:

XElement root = XElement.Parse("<Root><Settings><PresentationSettings></PresentationSettings></Settings></Root>");
XElement pSettings = root.Element("Settings").Element("PresentationSettings");
pSettings.Add(otherContentXml);
root.Save(fileName);
or
string formattedXml = root.ToString();

Upvotes: 2

Related Questions