Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most streamlined way of performing a XSLT transformation in ASP.NET?

Tags:

c#

xml

asp.net

xslt

In other words, is there a faster, more concise way of writing the following code:

//Create an object for performing XSTL transformations
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(HttpContext.Current.Server.MapPath("/xslt/" + xsltfile.Value), new XsltSettings(true, false), new XmlUrlResolver());

//Create a XmlReader object to read the XML we want to format
//XmlReader needs an input stream (StringReader)
StringReader sr = new StringReader(node.OuterXml);
XmlReader xr = XmlReader.Create(sr);

//Create a StringWriter object to capture the output from the XslCompiledTransform object
StringWriter sw = new StringWriter();

//Perform the transformation
xslt.Transform(xr, null, sw);

//Retrieve the transformed XML from the StringWriter object
string transformedXml = sw.ToString();

UPDATE (thanks for all the answers so far!):

Sorry for my vagueness: by "faster" and more "concise" I mean, am I including any unnecessary steps? Also, I would love a more "readable" solution if someone has one. I use this code in a small part of a web application I'm developing, and I'm about to move it to a large part of the application, so I want to make sure it's as neat as can be before I make the move.

Also, I get the XML from a static class (in a separate data access class library) which communicates with a database. I also manipulate the transformed XML string before shipping it off to a web page. I'm not sure if the input/response streams are still viable in this case.

One more thing: the XML and the XSLT supplied may change (users of the application can make changes to both), so I think I would be forced to compile each time.

like image 484
attack Avatar asked Aug 12 '09 20:08

attack


1 Answers

Here's code I did for my ASP.NET, which is very similar to yours:

  XDocument xDoc = XDocument.Load("output.xml");

        XDocument transformedDoc = new XDocument();
        using (XmlWriter writer = transformedDoc.CreateWriter())
        {
            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(XmlReader.Create(new StreamReader("books.xslt")));
            transform.Transform(xDoc.CreateReader(), writer);
        }

        // now just output transformedDoc
like image 96
Jim Schubert Avatar answered Nov 10 '22 03:11

Jim Schubert