Add new XElements with a new line to XDocument using PreserveWhitespace LoadOptions

I am trying to edit an XML file while maintaining its format:

<root> <files> <file>a</file> <file>b</file> <file>c</file> <file>d</file> </files> </root> 

So, I am loading an xml document using XDocument xDoc = XDocument.Load(path, LoadOptions.PreserveWhitespace);
But when I try to add new elements
xDoc.Root.Element("files").Add(new XElement("test","test")); xDoc.Root.Element("files").Add(new XElement("test2","test2"));
it adds to one line, so the output is as follows:

 <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 to a new line while retaining the original formatting? I tried using XmlWriter with Setting.Indent = true to save the XDocument, but as I see it, the elements are added to the same line when I use xDoc.Root.Element().Add()

Update: the full part of downloading, modifying and saving documents

 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) } } } } 
+5
source share
2 answers

The problem is with using LoadOptions.PreserveWhitespace . This seems to be the trump card of XmlWriterSettings.Indent - you basically said: "I care about this gap" ... "Oh, now I do not."

If you remove this option, just use:

 XDocument xDoc = XDocument.Load(path); 

... then he backs off accordingly. If you want to keep all original spaces and then indent only new elements, I think you will need to add this indent yourself.

+7
source

I had a similar problem and could solve it using the code below:

 var newPolygon = new XElement(doc.Root.GetDefaultNamespace() + "polygon"); groupElement.Add(newPolygon); groupElement.Add(Environment.NewLine); 

I hope this code can help some people ...

+5
source

Source: https://habr.com/ru/post/1209456/


All Articles