Question

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?

Was it helpful?

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.

OTHER TIPS

Well, an XmlWriter doesn't contain the output; typically, you have a backing object (maybe a StringBuilder or MemoryStream) that is the dumping place. In this case, StringBuilder is probably the most efficient... perhaps something like:

    StringBuilder sb = new StringBuilder();
    using (XmlWriter writer = XmlWriter.Create(sb))
    {
        // TODO write to writer via xslt
    }
    string xml = sb.ToString();
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    XmlElement el = doc.DocumentElement;

If you provide a writer, you provide a repository where an output generator is transferring data, thus the replay of Richard is good, you don't really need a string builder to send data from a reader to an XmlDocument!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top