如何使用Transformer将转换后的XML存入内存而非写入文件?
将XSLT转换结果存入内存对象的解决方案
当然可以实现!你完全不用把转换后的XML写入文件,直接把结果存到内存里的HashMap中就行,这样就能避免额外的IO操作,效率更高。
核心思路
StreamResult不仅可以接收File对象,还能接收Writer或OutputStream类型的参数。我们可以用**StringWriter(生成字符串形式的XML)或者ByteArrayOutputStream**(生成字节数组形式的XML)在内存中接收转换结果,之后再把结果存入你的transformedXMLMap里。
修改后的代码示例(字符串形式存储)
我们可以调整方法参数,把原来的outputPathname换成Map的key,方便后续取值:
public static void xmlProcessor(String stylesheetPathname, String inputPathname, String mapKey) throws TransformerException { TransformerFactory factory = TransformerFactory.newInstance(); Source stylesheetSource = new StreamSource(new File(stylesheetPathname).getAbsoluteFile()); Transformer transformer = factory.newTransformer(stylesheetSource); Source inputSource = new StreamSource(new File(inputPathname).getAbsoluteFile()); // 用StringWriter在内存中接收转换后的XML StringWriter resultWriter = new StringWriter(); Result outputResult = new StreamResult(resultWriter); // 执行转换,结果直接写入StringWriter transformer.transform(inputSource, outputResult); // 将XML字符串存入Map transformedXMLMap.put(mapKey, resultWriter.toString()); }
字节数组形式存储(可选)
如果后续需要处理二进制流形式的XML,可以改用ByteArrayOutputStream:
public static void xmlProcessor(String stylesheetPathname, String inputPathname, String mapKey) throws TransformerException { TransformerFactory factory = TransformerFactory.newInstance(); Source stylesheetSource = new StreamSource(new File(stylesheetPathname).getAbsoluteFile()); Transformer transformer = factory.newTransformer(stylesheetSource); Source inputSource = new StreamSource(new File(inputPathname).getAbsoluteFile()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Result outputResult = new StreamResult(baos); transformer.transform(inputSource, outputResult); // 将字节数组存入Map transformedXMLMap.put(mapKey, baos.toByteArray()); }
后续使用与清理
当你需要使用转换后的XML时,直接通过key从transformedXMLMap中取出即可:
// 取出字符串形式的XML String xmlContent = (String) transformedXMLMap.get("your-key"); // 或者取出字节数组形式的XML byte[] xmlBytes = (byte[]) transformedXMLMap.get("your-key");
使用完成后,记得调用transformedXMLMap.clear()来清空Map,避免内存占用过高。
内容的提问来源于stack exchange,提问作者JonLe
相关产品推荐
相关产品推荐

