Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 613
Yogesh Avatar asked Feb 08 '26 02:02

Yogesh


1 Answers

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();
like image 197
Chuck Savage Avatar answered Feb 12 '26 16:02

Chuck Savage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!