February 2, 2008

Converting A Class Heirarchy To Xml And Then Html

public class XXXToHtmlHelper
{
    private string xml;
    private Encoding encodingStandard;

    public XXXToHtmlHelper()
    {
        string tmpFileName = Path.GetTempFileName();
        if (Path.HasExtension(tmpFileName))
        {
            tmpFileName = Path.GetFileNameWithoutExtension(Path.GetTempFileName());
        }
        xml = Path.Combine(Path.GetTempPath(), tmpFileName + ".xml");
    }

    public void GenerateHtml(
        Encoding encoding, 
        string xsl, 
        XXX xxx,
        string html)
    {
        XXXToXmlFile(xml, encoding, xxx);
        XXX_XmlToHtml(xml, xsl, html);
        if (File.Exists(xml))
        {
            File.Delete(xml);
        }
    }

    private static void XXXToXmlFile(
        string xmlFile,
        Encoding encoding,
        XXX xxxObj)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            XmlTextWriter writer = new XmlTextWriter(ms, encoding);
            try
            {
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                xxxObj.ToXml(writer);
                writer.WriteEndDocument();
                writer.Flush();
            }
            finally
            {
                writer.Close();
            }
            File.WriteAllBytes(xml, ms.ToArray());
        }
    }


    private void XXX_XmlToHtml(string xmlInput, string htmlOutput)
    {
        XsltArgumentList args = new XsltArgumentList();
        args.AddParam("DATE", "", DateTime.Now.ToString("F"));
        args.AddParam("COMMENT", "", "Some comment");
        args.AddParam("USER", "", Environment.UserName);
        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(xslFile);
        MemoryStream ms = new MemoryStream();
        xslt.Transform(xmlInput, args, ms);
        File.WriteAllBytes(htmlOutput, ms.ToArray());
    }

}

No comments: