Java:将StreamResult转换为DOM

时间:2017-03-03 20:19:37

标签: java xml xslt dom xml-parsing

我正在使用saxon和xslt执行从一种xml格式到另一种xml格式的xslt转换,之后将结果xml转换为Java DOM以进一步处理它:

System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
TransformerFactory tFactory = TransformerFactory.newInstance();

Transformer transformer = tFactory.newTransformer(new StreamSource(new File("xslt.xsl")));
transformer.transform(new StreamSource(new File(inputXML)),
                                  new StreamResult(new File (outputXML)));

DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(outputXML);

在这种情况下我不喜欢创建中间outputXML文件。有可能避免它的产生吗?

2 个答案:

答案 0 :(得分:0)

DocumentResult result = new DocumentResult();

transformer.transform(new StreamSource(new File(inputXML)),result);

Document transformedDoc = result.getDocument();

答案 1 :(得分:0)

答案由@Andreas提供。如果有人感兴趣,我案例中的结果代码段看起来像这样:

System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
TransformerFactory tFactory = TransformerFactory.newInstance();

DOMResult xmlResult = new DOMResult();
Transformer transformer = tFactory.newTransformer(new StreamSource(new File("xslt.xsl")));
        transformer.transform(new StreamSource(new File(outputXML)),
                              xmlResult);

Document document = (Document) xmlResult.getNode();