我在stackoverflow帖子之一中遇到了以下示例-
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")));
}
}
在上面的示例中,我想将输入用作字符串,将输出用作字符串,并且仅从文件中读取xslt。有可能实现这一目标吗?
最佳答案
用StreamSource
https://docs.oracle.com/javase/7/docs/api/javax/xml/transform/stream/StreamSource.html#StreamSource(java.io.InputStream)看一下InputStream
构造函数
您可以像这样从string
创建输入:
InputStream input = new ByteArrayInputStream("<your string input>".getBytes(StandardCharsets.UTF_8));
Source text = new StreamSource(input);
并使用
string
和StringWriter
将输出作为StreamResult
: StringWriter outputWriter = new StringWriter();
StreamResult result = new StreamResult( outputWriter );
transformer.transform( text, result );
String outputAsString = outputWriter.getBuffer().toString();
关于java - 使用Java的XSLT,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42800632/