Punter Vicky
Punter Vicky

Reputation: 17032

XSLT using Java

I came across the below example in one of the stackoverflow posts -

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class TestMain {
    public static void main(String[] args) throws IOException, URISyntaxException, TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        Source xslt = new StreamSource(new File("transform.xslt"));
        Transformer transformer = factory.newTransformer(xslt);

        Source text = new StreamSource(new File("input.xml"));
        transformer.transform(text, new StreamResult(new File("output.xml")));
    }
}

In the above example , I would like to use input as a string and output as string and read only xslt from file. Is it possible to achieve this?

Upvotes: 2

Views: 644

Answers (2)

Punter Vicky
Punter Vicky

Reputation: 17032

I was able to do something similar to this which provided me the result -

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class TestMain {
    public static void main(String[] args) throws IOException, URISyntaxException, TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        Source xslt = new StreamSource(new File("transform.xslt"));

        Transformer transformer = factory.newTransformer(xslt);
String xmlData = "<xml><data>test</data>";
InputStream stream = new ByteArrayInputStream(xmlData.getBytes(StandardCharsets.UTF_8));
        Source text = new StreamSource(stream);

            StringWriter outWriter = new StringWriter();
            StreamResult result = new StreamResult( outWriter );
        transformer.transform(text, result);
            StringBuffer sb = outWriter.getBuffer(); 
            String finalstring = sb.toString();
    }
}

Upvotes: 0

mjlowky
mjlowky

Reputation: 1223

Have look at the StreamSource constructor with InputStream https://docs.oracle.com/javase/7/docs/api/javax/xml/transform/stream/StreamSource.html#StreamSource(java.io.InputStream)

You can create your input from string like this:

    InputStream input = new ByteArrayInputStream("<your string input>".getBytes(StandardCharsets.UTF_8));
    Source text = new StreamSource(input);

And get your output as string using StringWriter and StreamResult:

    StringWriter outputWriter = new StringWriter();
    StreamResult result = new StreamResult( outputWriter );

    transformer.transform( text, result );  

    String outputAsString = outputWriter.getBuffer().toString(); 

Upvotes: 3

Related Questions