我正在创建一个自定义XML文档。但我不希望XML作为文件可用,但我希望它在系统剪贴板中以字符串形式提供,以便我可以手动粘贴到现有文件。
我正在使用转换器将XML编写为:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
String output = writer.toString();
但我在这里得到一个空指针异常。
transformer.transform(source, new StreamResult(writer));
你能帮帮我吗。
答案 0 :(得分:1)
检查
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
来自here