How to: Populate an XML Tree with an XmlWriter (LINQ to XML)

One way to populate an XML tree is to use CreateWriter to create an XmlWriter, and then write to the XmlWriter. The XML tree is populated with all nodes that are written to the XmlWriter.

You would typically use this method when you use LINQ to XML with another class that expects to write to an XmlWriter, such as XslCompiledTransform.


One possible use for CreateWriter is when invoking an XSLT transformation. This example creates an XML tree, creates an XmlReader from the XML tree, creates a new document, and then creates an XmlWriter to write into the new document. It then invokes the XSLT transformation, passing in XmlReader and XmlWriter. After the transformation successfully completes, the new XML tree is populated with the results of the transformation.

string xslMarkup = @"<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl='' version='1.0'>
    <xsl:template match='/Parent'>
            <xsl:value-of select='Child1'/>
            <xsl:value-of select='Child2'/>

XDocument xmlTree = new XDocument(
    new XElement("Parent",
        new XElement("Child1", "Child1 data"),
        new XElement("Child2", "Child2 data")

XDocument newTree = new XDocument();
using (XmlWriter writer = newTree.CreateWriter())
    // Load the style sheet.
    XslCompiledTransform xslt = new XslCompiledTransform();
    xslt.Load(XmlReader.Create(new StringReader(xslMarkup)));

    // Execute the transformation and output the results to a writer.
    xslt.Transform(xmlTree.CreateReader(), writer);


This example produces the following output:

  <C1>Child1 data</C1>
  <C2>Child2 data</C2>

See Also

Build Date: