开发者

How to convert XmlTextWriter to string?

开发者 https://www.devze.com 2022-12-20 10:52 出处:网络
I am new to XSLT Transformation world. I\'m using XSLT to create an HTML file. How can I get t开发者_如何学Pythonhe output as string, so that I can save it to an HTML file?

I am new to XSLT Transformation world. I'm using XSLT to create an HTML file. How can I get t开发者_如何学Pythonhe output as string, so that I can save it to an HTML file?

Performing the transformation using below line:

objXtrans.Transform(objDoc, objArgLists, objXmlTxtWriter);

How can I convert objXmlTxtWriter to get the complete string generated via the Transform() method which can be saved as HTML?


If you want the transformation result to be a HTML file then transform to a file (stream), there is no need to first assemble a string in memory to write that complete string to a file.

Unfortunately you have not really told us which API you use, you mention XmlTextWriter in your subject line so I assume it is the .NET framework you use. Since .NET 2.0 the preferred XSLT processor is System.Xml.Xsl.XslCompiledTransform, if you look at its Transform method then it has several overloads transforming to a Stream so you could simply use code as follows:

XslCompiledTransform proc = new XslCompiledTransform();
proc.Load("sheet.xsl");
using (FileStream stream = File.OpenWrite("result.html"))
{
  proc.Transform(someInput, someArgumentList, stream);
}

You have a lot of options for the first argument, it can simply be a string with an input file name or URI, it can be an XmlReader, it can be an object implementing IXPathNavigable (such as an XmlDocument or XPathDocument).


This is really a question about Stream and TextWriter, not XML. All of the documentation for .NET's XSLT tools assumes you already know how to do stream- and text-based IO in .NET. If you don't, you may end up doing a lot of unnecessary work. (By "you" I mean "I", and by "may" I mean "did.")

Though Martin Honnen correctly observes that in your case you don't actually need to get your output to a string, here's how to do it. Note that this works with any method that writes to a TextWriter, not just XslCompiledTransform.Transform():

StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
   MethodThatWritesToATextWriter(sw);
}
string s = sb.ToString();

Though you can use a FileStream to write to a file in your specific case, FileStream is a Stream, not a TextWriter. You can only use it with Transform because one of the overloads of Transform takes a Stream as the output parameter. If you need to use a TextWriter, the tool for the job is StreamWriter:

using (StreamWriter sw = new StreamWriter(filename, append))
{
   MethodThatWritesToATextWriter(sw);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消