Evyatar Evyatar - 1 month ago 23
C# Question

Flat xml file c#

I'm wrting xml file with UTF-8 (without Bom) encoding as follow:

xmldecl.Encoding = "UTF-8";
dataDoc.InsertBefore(xmldecl, root);//dataDoc is XmlDocument object
using (var writer = new XmlTextWriter(targetPath, new UTF8Encoding(false)))
{
dataDoc.Save(writer);
}


My "problem" is the file is saved in one line instead of xml formatting,

I.e if i have the following xml:

<ElementA>
<ElementB/>
</ElementA>


With my code the xml file will be:

<ElementA><ElementB/></ElementA>


Instead of xml format.

How can i solve it?

*I'm try to open the file with Notepad++

Thanks.

Answer

XmlTextWriter has a property Formatting to define the way the output is written:

using (var writer = new XmlTextWriter(targetPath, new UTF8Encoding(false)))
{
    writer.Formatting = Formatting.Indented;
    dataDoc.Save(writer);
}