Export (0) Print
Expand All

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='http://www.w3.org/1999/XSL/Transform' version='1.0'>
    <xsl:template match='/Parent'>
        <Root>
            <C1>
            <xsl:value-of select='Child1'/>
            </C1>
            <C2>
            <xsl:value-of select='Child2'/>
            </C2>
        </Root>
    </xsl:template>
</xsl:stylesheet>";

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);
}

Console.WriteLine(newTree);

This example produces the following output:

<Root>
  <C1>Child1 data</C1>
  <C2>Child2 data</C2>
</Root>
Show:
© 2014 Microsoft