Tuesday, December 7, 2010

C#: Transform XML using XSL

I love strings, so I am going to use all in's and out's as strings. The "reading from file" part can be taken care of in the application code... so as to reduce IO overhead in this method itself.

WARNING: By the way this only works for simple 'standalone' XSL transforms. For chained XSLs (where main XSL includes additional XSL's using the syntax) it would not work and may get an IO exception while trying to load "blah.xsl" unless that file is also present in the executing folder.

public string TransformXml(string xml, string xsl)
{
string responseXml = string.Empty;
//Read XML
TextReader iXmlReader = new StringReader(xml);
XmlTextReader iXmlText = new XmlTextReader(iXmlReader);
XPathDocument iXPathDocument = new XPathDocument(iXmlText);

//Read XSL
TextReader iXslReader = new StringReader(xsl);
XmlTextReader iXslText = new XmlTextReader(iXslReader);

//Get ready
XslTransform xslt = new XslTransform();
xslt.Load(iXslText);
StringBuilder sb = new StringBuilder();
TextWriter tw = new StringWriter(sb);

//Transform
xslt.Transform(iXPathDocument, null, tw);
responseXml = sb.ToString();

return responseXml;
}

No comments:

Post a Comment

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.