Home
Manage Your Code
Snippet: Convert XML fragment using XSLT (C#)
Title: Convert XML fragment using XSLT Language: C#
Description: Convert XML fragment using XSLT stylesheet to HTML and return the resulting string Views: 1106
Author: Filip K Date Added: 12/15/2008
Copy Code  
1string result = string.Empty;
2
3// load XML from file

4StreamReader sr = new StreamReader(@"C:\_development\Floe\XmlXslConvert\topic_only.xml");
5XPathDocument myXPathDoc = new XPathDocument(sr);
6
7// load XSL from file

8XslTransform xslt = new XslTransform() ;
9xslt.Load(@"C:\_development\Floe\XmlXslConvert\help_item.xslt");
10
11// memory stream that will hold the transformation

12MemoryStream htmlOutput = new MemoryStream();
13
14XmlWriterSettings settings = new XmlWriterSettings();
15settings.OmitXmlDeclaration = true;
16settings.ConformanceLevel = ConformanceLevel.Fragment;
17settings.Encoding = Encoding.Unicode;
18
19// XML Writter user to write to the memory stream

20XmlWriter writterOut = XmlWriter.Create(htmlOutput, settings);
21
22// run the ransformation

23xslt.Transform(myXPathDoc, null, writterOut);
24
25// make sure everything gets pushed to the memory stream

26writterOut.Flush();
27
28// go to the start of the memory stream

29htmlOutput.Position = 0;
30
31// read from the memory stream

32StreamReader strm = new StreamReader(htmlOutput, Encoding.Unicode);
33
34// read the stream to text reader

35using (TextReader txtRead = strm)
36{
37	result = txtRead.ReadToEnd();
38}
39
40return result;