你必须写到你的StringWriter
:
import java.io.*;
public class StringWriterDemo {
public static void main(String[] args) {
String s = "Hello World";
// create a new writer
StringWriter sw = new StringWriter();
// write portions of strings
sw.write(s, 0, 4);
sw.write(s, 5, 6);
// write full string
sw.write(s);
// print result by converting to string
System.out.println("" + sw.toString());
}
}
不要做:
String ccdDoc = r.toString();
它只创建r
字符串的副本。然后您正在修改副本,但根本不修改StringWriter
.
做:
r.write("some content");
并访问作者包含的字符串,请执行以下操作:
String a_string = r.toString();
response.getOutputStream().write(a_string);
编辑 :
好的,所以您要问的内容与您提供的链接中的内容相去甚远,除了您必须写入 aStringWriter
而不是 a File
。
这可以通过以下方式实现:
1)建立一个xml文档:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
:
:
// Then write the doc into a StringWriter
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with StringWriter object to save to string
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
// Finally, send the response
byte[] res = xmlString.getBytes(Charset.forName("UTF-8"));
response.setCharacterEncoding("UTF-8");
response.getOutputStream().write(res);
response.flushBuffer();
这里的重点是:
StreamResult result = new StreamResult(new StringWriter());
代替:
StreamResult result = new StreamResult(new File("C:\\file.xml"));
你告诉我这是否还有什么不清楚的地方。