Xml InnerXml indentation problem

I have XmlDocument

:

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

      

When I install InnerXml

from <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 InnerXml

(i.e. <Desktop>

) starts at the right-indented column, but the rest InnerXml

retains its original indentation. I've tried many methods, but they all give the exact result. The methods I tried were as follows:

  • XmlTextWriter

    with Formatting = Formatting.Indented

    .
  • XmlWriter

    with XmlWriterSettings { Indent = true }

    .
  • Convert to XDocument

    using both of the above methods.
  • Use XmlDocumentFragment

    .

Can anyone point me in the direction of the recording? What am I doing wrong?

+3


source to share


1 answer


You have to use XDocument or XElement, XmlDocument is .Net 2.0, also deprecated.

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

      

+2


source







All Articles