Search code examples
xmlstringxsltjavax

XML to HTML using XSLT, input and output strings rather than files


I have worked through some XSLT tutorials, and all of them talk about using input and output files; In my specific case I have the XML and XSL all as strings - I read them from the database at runtime, and it changes depending on the record I am working with.

Is there a way to do some sort of conversion in order to manipulate the StreamSource, to give it the actual string instead of a file name?

I'm talking about:

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(new StreamSource(xsl));
        StreamSource src = new StreamSource(new FileInputStream(xml)); 

where xml and xls are both strings, containing the actual xml or the actual xsl.


Solution

  • Use a StringReader and use the StreamSource constructor that takes the reader as arguments.

    Here's a MCVE:

    package transformStrings;
    
    import java.io.StringReader;
    import java.io.StringWriter;
    
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.stream.StreamSource;
    
    public class transformFromStrings {
    
        public static void main(String[] args) throws TransformerException
        {
                StringReader xmlReader = new StringReader("<x/>");
                StreamSource xmlSource = new StreamSource(xmlReader);
    
                StringReader xslReader = new StringReader("<xsl:stylesheet version=\"1.0\"  xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"/\">OMG!</xsl:template></xsl:stylesheet>");
                StreamSource xslSource = new StreamSource(xslReader);
    
                TransformerFactory factory  = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer(xslSource);
    
                StringWriter resultWriter = new StringWriter();
                transformer.transform(xmlSource, new javax.xml.transform.stream.StreamResult(resultWriter));
                System.out.println(resultWriter.toString());
        }
    }