5

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?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
macleojw
  • 4,113
  • 10
  • 43
  • 63

3 Answers3

10

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.

Richard
  • 106,783
  • 21
  • 203
  • 265
7

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;
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

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!

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
user2991288
  • 361
  • 2
  • 5