1

I have the following program in which I am trying to generate a XML which is also generated through DOM parser. I want to store the generated XML into a string variable and it isn't working.

How can I store the generated XML into a string variable?

public class generatexml {

    public static void main(String[] args) {


        //************ wantt to store the generated xml in a string ********
        String s = generatexml();

    }

    public static StreamResult generatexml()
    {
          try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("kermail");
            doc.appendChild(rootElement);

            for(int i =0 ;i<5 ;i++ )

            {           
            Element invoiceReferenceNotificationMessage = doc.createElement("invoiceReferenceNotificationMessage");
            rootElement.appendChild(invoiceReferenceNotificationMessage);

            Element InvoiceReference = doc.createElement("abceReference");
            InvoiceReference.appendChild(doc.createTextNode("7815"));
            invoiceReferenceNotificationMessage.appendChild(abceReference);
        }


            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);

             StreamResult result = new StreamResult(System.out);
            transformer.transform(source, result);

            return result;

          } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
          } catch (TransformerException tfe) {
            tfe.printStackTrace();
          }

        }}
Luís Cruz
  • 14,780
  • 16
  • 68
  • 100
ndsfd ddsfd
  • 235
  • 1
  • 5
  • 13

1 Answers1

1

Your code seems correct to me . But looks like you need to do

        transformer.transform(source, result);
        System.out.println();
        return result;

other ways doing it are described at Is there a more elegant way to convert an XML Document to a String in Java than this code?

Update :-

      DOMSource source = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(source , result);
       writer.flush();
       String xmlString = writer.toString();
Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314