0

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();
    }
}
cody
  • 11,045
  • 3
  • 21
  • 36
p2018
  • 125
  • 1
  • 12
  • 1
    Possible duplicate of [Java : Convert formatted xml file to one line string](https://stackoverflow.com/questions/5511096/java-convert-formatted-xml-file-to-one-line-string) – Abhinav Dec 17 '18 at 17:12
  • 1
    Duplicate of https://stackoverflow.com/questions/2567416/xml-document-to-string – James Baker Dec 21 '18 at 15:58
  • 1
    Possible duplicate of [XML Document to String?](https://stackoverflow.com/questions/2567416/xml-document-to-string) – James Baker Dec 21 '18 at 16:12

1 Answers1

0

Solved by using approach as:

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);
    }
}
p2018
  • 125
  • 1
  • 12