java - How to assign output of java document into string variable?
问题描述
I have a below code which is the last step to generate XML. I want to store output XML to a string variable. How to do this in Java code? Currently, the output is in document format.
public static void main(String[] args) {
DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder icBuilder;
try {
icBuilder = icFactory.newDocumentBuilder();
Document doc = icBuilder.newDocument();
// Start of XML root element
Element mainRootElement = doc
.createElementNS("http://www.sampleWebSite.com/sampleWebSite/schema/external/message/actualDay/v1",
"NS1:actualDayResponse");
doc.appendChild(mainRootElement);
Transformer transformer =
TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult console = new StreamResult(System.out);
transformer.transform(source, console);
System.out.println("\nXML DOM Created Successfully..");
} catch (Exception e) {
e.printStackTrace();
}
}
解决方案
通过使用方法解决:
public static String toString(Document doc) {
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
} catch (Exception ex) {
throw new RuntimeException("Error converting to String", ex);
}
}
推荐阅读
- spring - 如何在对话服务中使用自动连线服务
- flutter - 在提供者的消费者小部件内部的测试中找不到小部件
- react-native - 世博会管理工作流程的条带/订阅付款
- node.js - 是否可以运行 npx 工具在 Azure 中执行包
- python - FancyArrowPatch 在散点图上未正确显示
- python - 熊猫从字符串中删除字符
- unity3d - Unity Game View 文本在本地显示为块
- ios - 获取点击手势的展开值
- android - 更改默认的android启动图标(建议的其他方法无效)
- javascript - 为什么Javascript中有一个全局对象?