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
withFormatting = Formatting.Indented
. -
XmlWriter
withXmlWriterSettings { 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?
source to share
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();
source to share