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?
+2
A:
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
2009-02-18 12:32:49
I'm always amazed at the way you make your answers so comprehensive and complete that there's hardly anything someone else could add. :-)
Cerebrus
2009-02-18 12:42:50
@Cerebrus - proven wrong by Richard ;-p
Marc Gravell
2009-02-18 13:14:04
+4
A:
You do not need an intermediate string, you can create an XmlWriter that writes directly into an XmlNode:
XmlDocument doc = new XmlDocument();
XmlWriter xw = doc.CreateNavigator().AppendChild();
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
2009-02-18 12:53:56