我有一个XML转换过程,我将输出转换的XML写入文件。但不是将其存储在文件中,而是将其存储在字符串变量中。我创建了一个字符串变量,请告知我如何将生成的XML存储在字符串变量中(msgxml而不是写入文件)。
String msgxml;
System.setProperty("javax.xml.transform.TransformerFactory",
"org.apache.xalan.processor.TransformerFactoryImpl");
FileInputStream xml = new FileInputStream(xmlInput);
FileInputStream xsl = new FileInputStream(xslInput);
FileOutputStream os = new FileOutputStream(outputXmlFile);
TransformerFactory tFactory = TransformerFactory.newInstance();
// Use the TransformerFactory to process the stylesheet source and produce a Transformer
StreamSource styleSource = new StreamSource(xsl);
Transformer transformer = tFactory.newTransformer(styleSource);
StreamSource xmlSource = new StreamSource(xml);
StreamResult result = new StreamResult(os);
//here we are storing it in a file ,
try {
transformer.transform(xmlSource, result);
} catch (TransformerException e) {
e.printStackTrace();
}
答案 0 :(得分:1)
一种方法是使用ByteArrayOutputStream
代替FileOutputStream
:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory tFactory = TransformerFactory.newInstance();
...
StreamSource xmlSource = new StreamSource(xml);
StreamResult result = new StreamResult(baos); // write to the byte array stream
//here we are storing it in a file ,
try {
transformer.transform(xmlSource, result);
}
...
msgxml = baos.toString("UTF-8"); // get contents of stream using UTF-8 encoding
另一种解决方案是使用java.io.StringWriter
:
StringWriter stringWriter = new StringWriter();
StreamResult result = new StreamResult(stringWriter);
...
msgxml = stringWriter.toString();