Add new XElements with new line in XDocument with PreserveWhitespace LoadOptions C#



I'm trying to edit XML file saving its format:



<root>
<files>
<file>a</file>

<file>b</file>
<file>c</file>



<file>d</file>
</files>
</root>


So i load xml document using

XDocument xDoc = XDocument.Load(path, LoadOptions.PreserveWhitespace);

But when i'm trying to add new elements

xDoc.Root.Element("files").Add(new XElement("test","test")); xDoc.Root.Element("files").Add(new XElement("test2","test2"));

it adds in the same line, so output is like:



<root>
<files>
<file>a</file>

<file>b</file>
<file>c</file>



<file>d</file>
<test>test</test><test2>test2</test2></files>
</root>


So how can i add new elements each on new line saving initial formatting? I tried to use XmlWriter with Setting.Indent = true to save XDocument, but as i see, elements are added to the same line, when i use xDoc.Root.Element().Add()


Update: full part of programm loading, modifiyng and saving document



using System;
using System.Xml;
using System.Xml.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string path = @".\doc.xml";
XDocument xDoc = XDocument.Load(path, LoadOptions.PreserveWhitespace);

//when i debug i see in "watch" that after these commands new elements are already added in same line
xDoc.Descendants("files").First().Add(new XElement("test", "test"));
xDoc.Descendants("files").First().Add(new XElement("test2", "test2"));

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
settings.IndentChars = "\t";

using (XmlWriter writer = XmlTextWriter.Create(path, settings))
{
xDoc.Save(writer);
//Here i also tried save without writer - xDoc.Save(path)
}
}
}
}

No comments:

Post a Comment