Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply XSLT on in-memory XML and returning in-memory XML

Tags:

c#

.net

xml

xslt

I am looking for a static function in the .NET framework which takes an XML snippet and an XSLT file, applies the transformation in memory, and returns the transformed XML.

I would like to do this:

string rawXml = invoiceTemplateDoc.MainDocumentPart.Document.InnerXml;
rawXml = DoXsltTransformation(rawXml, @"c:\prepare-invoice.xslt"));

// ... do more manipulations on the rawXml

Alternatively, instead of taking and returning strings, it could be taking and returning XmlNodes.

Is there such a function?

like image 756
Jan Willem B Avatar asked May 18 '10 09:05

Jan Willem B


3 Answers

You can use the StringReader and StringWriter classes :

string input = "<?xml version=\"1.0\"?> ...";
string output;
using (StringReader sReader = new StringReader(input))
using (XmlReader xReader = XmlReader.Create(sReader))
using (StringWriter sWriter = new StringWriter())
using (XmlWriter xWriter = XmlWriter.Create(sWriter))
{
    XslCompiledTransform xslt = new XslCompiledTransform();
    xslt.Load("transform.xsl");
    xslt.Transform(xReader, xWriter);
    output = sWriter.ToString();
}
like image 169
Thomas Levesque Avatar answered Sep 19 '22 12:09

Thomas Levesque


A little know feature is that you can in fact transform data directly into a XmlDocument DOM or into a LINQ-to-XML XElement or XDocument (via the CreateWriter() method) without having to pass through a text form by getting an XmlWriter instance to feed them with data.

Assuming that your XML input is IXPathNavigable and that you have loaded a XslCompiledTransform instance, you can do the following:

XmlDocument target = new XmlDocument(input.CreateNavigator().NameTable);
using (XmlWriter writer = target.CreateNavigator().AppendChild()) {
  transform.Transform(input, writer);
}

You then have the transformed document in the taget document. Note that there are other overloads on the transform to allow you to pass XSLT arguments and extensions into the stylesheet.

If you want you can write your own static helper or extension method to perform the transform as you need it. However, it may be a good idea to cache the transform since loading and compiling it is not free.

like image 21
Lucero Avatar answered Sep 21 '22 12:09

Lucero


Have you noticed that there is the XsltCompiledTransform class?

like image 24
Tomalak Avatar answered Sep 22 '22 12:09

Tomalak