【问题标题】:XSL transformation of an input XML using java使用 java 对输入 XML 进行 XSL 转换
【发布时间】:2015-05-19 09:36:14
【问题描述】:

我只是想了解如何使用 Java 编码使用 XSLT 文件转换输入 XML。

有很多问题或多或少与我的问题相关,但我并不清楚,所以我以一种简单易懂的方式提出了我的问题。

任何人都可以帮助我解决不同的可能性,以及一个简单的例子来理解使用 java 进行的转换。

【问题讨论】:

标签: java xml xslt


【解决方案1】:

这是一个使用 javax.xml 的简单示例:

/**
 * Write the xml report to the file.
 *
 * NB: Transforms it into html on the fly.
 *
 * @param file Where to put it.
 * @param xml - What to put in it.
 */
protected void writeReport(File file, StringBuilder xml) {
    try {
        // Transform it through the xsl.
        Source xslt = new StreamSource(this.getClass().getResourceAsStream("SavedReport.xsl"));
        // Build a transformer.
        Transformer transformer = factory.newTransformer(xslt);
        // Make URIs resolve to the same location as the xsl.
        transformer.setURIResolver(justTheNameMeansLocal);
        // Make a string stream out of the xml.
        Source source = new StreamSource(new ByteArrayInputStream(xml.toString().getBytes("UTF-8")));
        // Transform it straight into the output file.
        try (FileOutputStream stream = new FileOutputStream(file)) {
            StreamResult result = new StreamResult(stream);
            transformer.transform(source, result);
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.writeLog(ME + "writeReport", ex, Logger.LOG_ERROR);
    } catch (TransformerException ex) {
        Logger.writeLog(ME + "writeReport", ex, Logger.LOG_ERROR);
    } catch (FileNotFoundException ex) {
        Logger.writeLog(ME + "writeReport", ex, Logger.LOG_ERROR);
    } catch (IOException ex) {
        Logger.writeLog(ME + "writeReport", ex, Logger.LOG_ERROR);
    }
}

/**
 * Resolve URI that are just a name to local.
 */
static class JustTheNameMeansLocal implements URIResolver {

    public Source resolve(String href, String base) throws TransformerException {
        // Name only - resolve to local - otherwise hand off the resolution to default.
        return href.contains("\\") ? null : new StreamSource(SavedHTMLReport.class.getResourceAsStream(href));
    }

}
private static final URIResolver justTheNameMeansLocal = new JustTheNameMeansLocal();
// Transformer factory.
protected static final TransformerFactory factory = TransformerFactory.newInstance();

【讨论】:

  • 嗨@OldCurmudgeon,我通过你给出的简单例子理解了逻辑。当我想在 XML 文件上按顺序应用多个 XSLT 时,是否可以应用相同的代码。即第一个转换的输出应该用作第二个转换的输入,...
  • @Sonu - 看看thisthis
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 2013-02-05
  • 2014-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多