Search code examples
c#xmlxmldocumentindentation

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:

  • XmlTextWriter with Formatting = Formatting.Indented.
  • XmlWriter with XmlWriterSettings { Indent = true }.
  • Converting to XDocument with both the above methods.
  • Using XmlDocumentFragment.

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


Solution

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