3

We have a method that writes XML into an XmlWriter, we use this to generate a stream of XML directly without having to go via some form of DOM. However there are occasions where we do want to create a DOM. One approach would be to always build a DOM and to stream from that (to cover both requirements), but we like the performance of writing XML directly. Therefore we want to build a DOM from an XmlWriter.

See How to create a XmlDocument using XmlWriter in .NET? for an example of how to create an XmlDocument from an XmlWriter, albeit using a slightly off-piste code pattern. Are there similar options if I want an XDocument (or XElement subtree) instead?

Community
  • 1
  • 1
redcalx
  • 8,177
  • 4
  • 56
  • 105

1 Answers1

9

Have a look at the XContainer.CreateWriter Method:

XContainer.CreateWriter Method

Creates an XmlWriter that can be used to add nodes to the XContainer.

Both XDocument and XElement are XContainers.

Example:

XDocument doc = new XDocument();
using (XmlWriter writer = doc.CreateWriter())
{
    // Do this directly 
    writer.WriteStartDocument();
    writer.WriteStartElement("root");
    writer.WriteElementString("foo", "bar");
    writer.WriteEndElement();
    writer.WriteEndDocument();
    // or anything else you want to with writer, like calling functions etc.
}
d219
  • 2,707
  • 5
  • 31
  • 36
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 2
    I was thinking the same, the only thing to consider from a perfomance point of view is that on writer.Close() the Add() function of XDocument is used to add the complete XML. – Marco Sep 03 '13 at 13:05
  • @Marco. Can you explain that a bit further? Looks like I get an XmlWellFormedWriter returned so not sure how that is connected to the XDocument and therefore what happens when the writer is closed. – redcalx Sep 03 '13 at 14:49
  • OK I see it. XNodeBuild is used under the hood and actually just uses a StringBuilder to build an XML string and then do one big parse at the end. Thanks for the pointer. – redcalx Sep 03 '13 at 14:53
  • where is the given XmlWriter? – Blue Clouds Apr 13 '18 at 10:46