Tuesday, 7 June 2011

C#.NET 4 - Transforming XML and XSL documents with settings and parameters

This following example takes a path to an XML file, a path to an XSL file and optional parameters to pass to the XSL file. The XSL file will decorate any xsl:param tags with these values.

The example also includes settings objects to show how settings can be applied to the tranformation and the loading of the XML.


Example C# Code
string xsltResult = string.Empty;
 
try
{
    // XML Settings
    XmlReaderSettings xmlSettings = new XmlReaderSettings();
    xmlSettings.XmlResolver = null;
    xmlSettings.IgnoreComments = true;
    xmlSettings.DtdProcessing = DtdProcessing.Ignore;
    xmlSettings.ValidationType = ValidationType.None;
 
    // Attaches an action to the valiation event handler. This will write out error messages in the Output pane.
    #if DEBUG
    xmlSettings.ValidationEventHandler += (sender, e) =>
    {
        Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message));
    };
    #endif
 
    // XSLT Settings
    XmlReaderSettings xsltSettings = new XmlReaderSettings();
    xsltSettings.XmlResolver = null;
    xsltSettings.DtdProcessing = DtdProcessing.Ignore;
    xsltSettings.ValidationType = ValidationType.None;
 
    // Attaches an action to the valiation event handler. This will write out error messages in the Output pane.
    #if DEBUG
    xsltSettings.ValidationEventHandler += (sender, e) =>
    {
        Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message));
    };
    #endif
 
    // Init params
    XsltArgumentList xslArgs = new XsltArgumentList();
    if (parameters != null)
    {
        foreach (KeyValuePair<string, string> param in parameters)
            xslArgs.AddParam(param.Key, string.Empty, param.Value);
    }
 
    // Load XML
    using (XmlReader reader = XmlReader.Create(xmlPath, settings))
    {
        // Load XSL
        XsltSettings xslSettings = new XsltSettings(true, true); // Need to enable the document() fucntion
 
        using(XmlReader xslSource = XmlReader.Create(xslPath, xsltSettings))
        {
            XslCompiledTransform xsltDoc = new XslCompiledTransform();
            xsltDoc.Load(xslSource, xslSettings, new XmlUrlResolver());
 
            // Transform
            using (var sw = new UTF8StringWriter())
            {
                        XmlWriterSettings settings = new XmlWriterSettings();
                        settings.Encoding = Encoding.UTF8;
                        settings.OmitXmlDeclaration = true;
 
                using(var xw = XmlWriter.Create(sw,settings))
                {
                    xsltDoc.Transform(reader, xslArgs, sw);
                }
 
                xsltResult = sw.ToString();
            }
        }
    }
}
catch {} // custom error handling here

No comments: