Saturday, November 28, 2015

Insert XSL Stylesheet reference in the XML document using C# program



Here is the code snippet to insert the XSL style sheet reference in the XML document.

Thanks
Adam


XmlDocument xmlDoc = new XmlDocument();
using (MemoryStream memStreamXml = new MemoryStream())
{

     XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
     xmlWriterSettings.Encoding =
Encoding.UTF8;
     
XmlWriter xmlWriter = XmlWriter.Create(memStreamXml, xmlWriterSettings);
     xmlSer =
new XmlSerializer(typeof(SomeClass));
     xmlSer.Serialize(xmlWriter, SomeClassObject);

     memStreamXml.Seek(0, SeekOrigin.Begin);
     xmlDoc.Load(memStreamXml);

}
// Now add the stylesheet processing

// instruction to the XML document

XmlProcessingInstruction newPI;
String PItext = string.Format("type='text/xsl' href='{0}'", xslFileName);
newPI = xmlDoc.CreateProcessingInstruction(
"xml-stylesheet", PItext);
xmlDoc.InsertAfter(newPI, xmlDoc.FirstChild);
// Now write the document
// out to the final output stream
using (StreamWriter streamWriter = new StreamWriter(xmlFileName, false, Encoding.UTF8))
{
    using (XmlWriter xmlWriter = XmlWriter.Create(streamWriter)
    {

       xmlDoc.WriteTo(xmlWriter);

    }
}

All Blogs so far ...