如何将Java文档的输出分配为字符串变量?

时间:2018-12-17 16:17:40

标签: java

我有一个下面的代码,这是生成XML的最后一步。我想将输出XML存储到字符串变量。如何用Java代码做到这一点?当前,输出为文档格式。

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();
    }
}

1 个答案:

答案 0 :(得分:0)

通过使用以下方法解决:

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);
    }
}