0

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.

1 Answer 1

2

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());
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I do the same myself, I often give brief answers that assume people know the basics. It's good to make them do some work. But sometimes I relent and take them the next step on their journey.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.