首页 > 解决方案 > 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();
    }
}

标签: java

解决方案


通过使用方法解决:

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

推荐阅读