The way I figured it out is as follows:
- Create a stream:
var stream = new MemoryStream();
- Create your XML and save it to the stream:
var writerSettings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = Environment.NewLine,
NewLineHandling = NewLineHandling.Replace,
OmitXmlDeclaration = true,
};
using (var xrmService = new XrmServiceContext(context.Service))
using (XmlWriter writer = XmlWriter.Create(stream, writerSettings))
{
writer.WriteStartElement("xyz");
writer.WriteElementString("abc", "123");
...
writer.WriteEndElement();
writer.Flush();
}
- Convert Stream to String in order to be able reformat
string stringXml = Encoding.UTF8.GetString(stream.ToArray()).Replace(" />", "/>");
Convert String back to Stream in order to be able to write to file
byte[] byteArray = Encoding.UTF8.GetBytes(stringXml);
MemoryStream formattedStream = new MemoryStream(byteArray);
Write Stream to file
using (FileStream file = new FileStream(@"filepath\file.xml",
FileMode.Create, FileAccess.Write))
{
formattedStream.CopyTo(file);
file.Flush();
}
formattedStream.Flush();
Resources that has help me to achieve this: