Saving XElement asynchronously

I am currently writing an XML Tree (XElement) to a file synchronously using XmlWriter, specifically via XElement.WriteTo(XmlWriter) on the root element. I'm trying to make that asynchronous (with an await). XmlWriter can be made asynchronous (XmlWriterSettings.Async = true), and has an async version for many of its methods. However, it doesn't have methods to write an XElement (async or not), and there is no async version of XElement.WriteTo(XmlWriter).

What API can be used to write an XElement to a file asynchronously?


1 Answers Saving XElement asynchronously

XmlWriter has a method XmlWriter.WriteNodeAsync(XmlReader, Boolean) to which you can pass the XmlReader returned by XNode.CreateReader() e.g. like so:

public static class XElementExtensions
    public static async Task WriteToAsync(this XContainer element, Stream stream, bool defAttr = true, bool indent = false)
        var settings = new XmlWriterSettings
            Async = true,
            CloseOutput = false,
            Indent = indent,

        using (var writer = XmlWriter.Create(stream, settings))
        using (var reader = element.CreateReader())
            await writer.WriteNodeAsync(reader, defAttr);

Then if you have some Stream stream you could write to it as follows:

await element.WriteToAsync(stream, false, true);

Sample .Net fiddle.

1 year ago