我现在可以使用以下代码生成 HTML 文件:
FileInputStream xml = new FileInputStream("original.xml");
FileInputStream xsl = new FileInputStream("converter.xsl");
FileOutputStream out = new FileOutputStream("result.html");
Source xmlDoc = new StreamSource(xml);
Source xslDoc = new StreamSource(xsl);
Result result = new StreamResult(out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer trans = factory.newTransformer(xslDoc);
trans.transform(xmlDoc, result);
但是,我想生成一个 Java 字符串而不是外部 HTML 文件,以便我可以通过 Ajax 回调将结果传递回我的 JSP 页面。我怎样才能修改这段代码来做到这一点?
最佳答案
将 FileOutputStream
替换为 StringWriter
,然后在最后调用 StringWriter
上的 toString()
。像这样的东西。
FileInputStream xml = new FileInputStream("original.xml");
FileInputStream xsl = new FileInputStream("converter.xsl");
StringWriter writer = new StringWriter();
Source xmlDoc = new StreamSource(xml);
Source xslDoc = new StreamSource(xsl);
Result result = new StreamResult(writer);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer trans = factory.newTransformer(xslDoc);
trans.transform(xmlDoc, result);
String outputString = writer.toString();
关于java - 在 Java 中使用 XSLT 将 XML 转换为 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21665009/