XMLWriter formatting when appending to existing XML

137 views Asked by At

I've got an existing XML file. New content is added to it via XmlWriter (or XmlTextWriter, doesn't matter which as both exhibit the same behaviour).

The problem:
The new content is not formatted with indentation.

Sample output by XmlWriter with Indent=true and IndentChars set to space:

<?xml version="1.0"?>
<RootContext Type="ETSP">
<Root><Element1>1</Element1><Element2>2</Element2><Element3>3</Element3><Element4>4</Element4><Element5>5</Element5></Root></RootContext>

Using this sample code to create additional XML content adding it to the existing XML (<RootContext Type="ETSP"> ...):

        XElement srcTree = new XElement("Root",
            new XElement("Element1", 1),
            new XElement("Element2", 2),
            new XElement("Element3", 3),
            new XElement("Element4", 4),
            new XElement("Element5", 5));

The existing XML I'm appending to is read via XmlTextReader/XElement.Load().

Now: this happens when creating a new XML - using the same settings - containing just the generated snippet from above:

<?xml version="1.0"?>
<Root>
   <Element1>1</Element1>
   <Element2>2</Element2>
   <Element3>3</Element3>
   <Element4>4</Element4>
   <Element5>5</Element5>
</Root>

Great. Properly indented, formatted - just what I want.

Now - how can I get the indented formatting when appending to existing XML content?

1

There are 1 answers

0
cacau On BEST ANSWER

FWIW - using the approach suggested by John Saunders and going to XDocument works just fine.

The new content is appended to the existing document with the desired formatting.