Reputation: 840
In my code below, I’m modifying the XML file with XSLT using SAXON
import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class SaxonImplementation {
public static void simpleTransform(String sourcePath, String xsltPath,
String resultDir) {
TransformerFactory tFactory = TransformerFactory.newInstance();
try {
Transformer transformer = tFactory
.newTransformer(new StreamSource(new File(xsltPath)));
transformer.transform(new StreamSource(new File(sourcePath)),
new StreamResult(new File(resultDir)));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.setProperty("javax.xml.transform.TransformerFactory",
"net.sf.saxon.TransformerFactoryImpl");
simpleTransform("first.xml", "newxsl.xslt", "second.xml");
}
}
Now instead of modifying the XML file, I want to modify an XML string. How shall I proceed here? The transformer.transform method requires an XML source file and the result file. How can I provide an XML string instead of a file and get the results in the form of Stream?
Upvotes: 2
Views: 539
Reputation: 32980
You can create a StreamSource
for a java.io.Reader
therefore wrap the XML string in a StringReader
and then in a StreamSource
and pass that to the transformer:
String xml = ...
transformer.transform(new StreamSource(new StringReader(xml)), ...
Same is true for the StreamResult
, you can use any OutputStream
or Writer
to create a StreamResult
.
And this works for any Trax
implementation not just for Saxon.
Upvotes: 3