1

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?

cacau
  • 3,606
  • 3
  • 21
  • 42
  • I'm surprised you can append data at all. How about don't do that, read into XDocument, append to XDocument, write whole thing out with indentation? – John Saunders Jun 17 '15 at 07:30
  • Well - why not? Load XML using TextReader then you've got your document as `XElements`, voila.. I'll try using XDocument, thanks for the hint – cacau Jun 17 '15 at 07:33
  • 1
    Can you share the code that is actually doing the writing? – dbc Jun 17 '15 at 18:55
  • There's nothing here that anyone could use to reproduce your issue. `Ident=true` is ignored when there is significant whitespace written, but it could be anything. Add some code. Though I'm inclined to agree with @JohnSaunders - there should be an easier way of doing this that doesn't involve using such low level APIs. – Charles Mager Jun 18 '15 at 08:51
  • @JohnSaunders Thanks - using `XDocument` directly works fine! – cacau Jul 22 '15 at 07:40

1 Answers1

0

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.

cacau
  • 3,606
  • 3
  • 21
  • 42