gpt4 book ai didi

java - 使用 Java 的 XSLT

转载 作者:行者123 更新时间:2023-11-30 06:50:53 24 4
gpt4 key购买 nike

我在 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。可以实现这个目标吗?

最佳答案

查看带有 InputStreamStreamSource 构造函数 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);

并使用 StringWriterStreamResult 将输出作为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com