Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform XML as a string w/o using files in .NET?

Tags:

c#

xml

xslt

Let's say I have two strings:

  • one is XML data
  • and the other is XSL data.

The xml and xsl data are stored in database columns, if you must know.

How can I transform the XML in C# w/o saving the xml and xsl as files first? I would like the output to be a string, too (HTML from the transformation).

It seems C# prefers to transform via files. I couldn't find a string-input overload for Load() in XslCompiledTransform. So, that's why I'm asking.

like image 584
Bill Paetzke Avatar asked Mar 05 '10 03:03

Bill Paetzke


People also ask

Can we convert XML to string?

Java Code to Convert an XML Document to String For converting the XML Document to String, we will use TransformerFactory , Transformer and DOMSource classes. "</BookStore>"; //Call method to convert XML string content to XML Document object.

How do I read an XML file as a string?

In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.

How can XML documents be transformed?

There are many methods you can use to transform XML documents including the XSLTRANSFORM function, an XQuery update expression, and XSLT processing by an external application server.

What can be used to transform XML into HTML?

XSLT is commonly used to convert XML to HTML, but can also be used to transform XML documents that comply with one XML schema into documents that comply with another schema. XSLT can also be used to convert XML data into unrelated formats, like comma-delimited text or formatting languages such as troff.


1 Answers

Here's what I went with. It's a combination of your answers. I voted up the answers that inspired this:

string output = String.Empty; using (StringReader srt = new StringReader(xslInput)) // xslInput is a string that contains xsl using (StringReader sri = new StringReader(xmlInput)) // xmlInput is a string that contains xml {     using (XmlReader xrt = XmlReader.Create(srt))     using (XmlReader xri = XmlReader.Create(sri))     {         XslCompiledTransform xslt = new XslCompiledTransform();         xslt.Load(xrt);         using (StringWriter sw = new StringWriter())         using (XmlWriter xwo = XmlWriter.Create(sw, xslt.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML         {             xslt.Transform(xri, xwo);             output = sw.ToString();         }     } } 

Note: this statement is required in the xsl, in order to output as HTML:

<xsl:output method="html" omit-xml-declaration="yes" /> 
like image 187
Bill Paetzke Avatar answered Sep 24 '22 02:09

Bill Paetzke