Apply XSLT on XML in memory and return XML in memory

I am looking for a static function in the .NET framework that accepts an XML fragment and XSLT file, applies in-memory transform, and returns the converted 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 accepting and returning strings, it can accept and return XmlNodes.

Is there such a function?

+4
source share
3 answers

The minuscule feature is that you can actually convert the data directly to the XmlDocument DOM or to the LINQ-to-XML XElement or XDocument (via the CreateWriter() method) without having to go through the text form, getting an XmlWriter instance to feed the data.

Assuming your XML input is IXPathNavigable and that you downloaded an XslCompiledTransform instance, you can do the following:

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

Then you converted the document into a taget document. Note that there are other overloads on transform so that you can pass XSLT arguments and extensions to the stylesheet.

If you want, you can write your own static helper or extension method to perform the conversion as needed. However, it might be a good idea to cache the conversion, since downloading and compiling are not free.

+5
source

You can use the StringReader and StringWriter :

 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(); } 
+7
source

Have you noticed that there is an XsltCompiledTransform class ?

+1
source

Source: https://habr.com/ru/post/1310096/


All Articles