Friday, February 9, 2007

Transforming XML with XSL: Method 1

There are several ways to transform an XML document with XSL. This is one approach that includes passing parameters to the XSL and assumes the transformation is targeted for a <div> element. You'll need the following namespaces added, assuming this is an ASP.NET website: System.IO, System.Xml.Xsl, System.Xml.XPath. This should be wrapped in a try/catch block.
XPathDocument xpathDocument = new XPathDocument(this.Server.MapPath("/xml/test.xml"));
XslCompiledTransform xpathTransform = new XslCompiledTransform();
StringWriter xpathWriter = new StringWriter();
XsltArgumentList xslArg = new XsltArgumentList();
xslArg.AddParam("path", "", imgPath); /* imgPath defined elsewhere */
xslArg.AddParam("country", "", country); /* country defined elsewhere */
xpathTransform.Transform(xpathDocument, xslArg, xpathWriter);
divXml.InnerHtml = xpathWriter.ToString(); /* divXml is a control on the ASPX page */

UPDATE: Why would you need this approach versus using the Xml control? I ran into a situation where some legacy XSL used the document() function and called a file on the network. I needed to 1) use impersonation and 2) set XmlSetting when I called Load().

No comments: