[英]Storing the contents in a String variable rather than a file
我有一個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();
}
一種方法是使用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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.