Search code examples
c#xmlxmlwriter

Creating an XML Element object from an XML Writer in C#


I'm writing a Windows service in C#. I've got an XmlWriter which is contains the output of an XSLT transformation. I need to get the XML into an XMLElement object to pass to a web service.

What is the best way to do this?


Solution

  • You do not need an intermediate string, you can create an XmlWriter that writes directly into an XmlNode:

    XmlDocument doc = new XmlDocument();
    using (XmlWriter xw = doc.CreateNavigator().AppendChild()) {
      // Write to `xw` here.
      // Nodes written to `xw` will not appear in the document 
      // until `xw` is closed/disposed.
    }
    

    and pass xw as the output of the transform.

    NB. Some parts of the xsl:output will be ignored (e.g. encoding) because the XmlDocument will use its own settings.