我在 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。可以实现这个目标吗?
最佳答案
查看带有 InputStream
的 StreamSource
构造函数 https://docs.oracle.com/javase/7/docs/api/javax/xml/transform/stream/StreamSource.html#StreamSource(java.io.InputStream)
您可以像这样从字符串
创建输入:
InputStream input = new ByteArrayInputStream("<your string input>".getBytes(StandardCharsets.UTF_8));
Source text = new StreamSource(input);
并使用 StringWriter
和 StreamResult
将输出作为 string
:
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/