Saturday, February 27, 2016

Create HTML content using XML and XSLT in memory


There was a need to create HTML content from XML and XSLT.

Also only the XSLT file will be loaded from the disk. The XML and HTML should be created in memory and returned as a string.

Here is the code snippet on how to achieve this.

Happy coding.

Cheers
Adam


#region Create HTML File
                #region Generate XML String in memory based on the C# class object

               
string xmlMemString = string.Empty;
                using (MemoryStream memStreamXml = new MemoryStream())
                {
                    System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
                   xmlWriterSettings.Encoding = System.Text.Encoding.UTF8;
                    System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(memStreamXml, xmlWriterSettings);
                    using (xmlWriter)
                    {
                        System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(CSharpClass));
// This cSharpClassObject contains the XML data which needs to be serialized
                        xmlSer.Serialize(xmlWriter, cSharpClassObject);
                    }
                    memStreamXml.Seek(0, SeekOrigin.Begin);
                    StreamReader xmlMemReader = new StreamReader(memStreamXml);
                    xmlMemString = xmlMemReader.ReadToEnd();
                    xmlMemReader.Close();
                }

                #endregion

                #region
Read XML file and convert to HTML

                System.Xml.
XmlDocument xdoc = new System.Xml.XmlDocument();
                xdoc.LoadXml(xmlMemString);
               
// load xslt to do transformation
                System.Xml.Xsl.XslCompiledTransform xsl = new System.Xml.Xsl.XslCompiledTransform();
                xsl.Load(xslFileName); // xslFileName is the XSLT style sheet with full path. This contains the instructions to convert the XML content into HTML.

               
// load xslt arguments to load specific page from xml file
                // this can be used if you have multiple pages
                // in your xml file and you loading them one at a time
              System.Xml.Xsl.XsltArgumentList xslarg = new System.Xml.Xsl.XsltArgumentList();
                MemoryStream htmlMemStream = new MemoryStream();
                xsl.Transform(xdoc, xslarg, htmlMemStream);
                htmlMemStream.Flush();
                reportHtml = System.Text.Encoding.UTF8.GetString(htmlMemStream.ToArray());
                #endregion

#endregion

 

All Blogs so far ...