title: Writing to a XML file in Java
body: <p>I am working on the following code:</p>
  
  <pre><code>import java.io.*;
  import javax.xml.parsers.*;
  import javax.xml.transform.*;
  import javax.xml.transform.dom.*;
  import javax.xml.transform.stream.*;
  import org.w3c.dom.*;
  
  public class CreatXMLFile {
    public static void main(String[] args) throws Exception {
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  //    System.out.print("Enter number to add elements in your XML file: ");
  //    String str = bf.readLine();
      int no=2;
  //    System.out.print("Enter root: ");
      String root = "SMS";
      DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
  
          DocumentBuilder documentBuilder =documentBuilderFactory.newDocumentBuilder();
  
          Document document = documentBuilder.newDocument();
  
      Element rootElement = document.createElement(root);
  
          document.appendChild(rootElement);
  //    for (int i = 1; i &lt;= no; i++)
  //      System.out.print("Enter the element: ");
  //      String element = bf.readLine();
        String element ="Number";
        System.out.print("Enter the Number: ");
        String data = bf.readLine();
        Element em = document.createElement(element);
        em.appendChild(document.createTextNode(data));
        rootElement.appendChild(em);
  
        String element1 ="message";
        System.out.print("Enter the SMS: ");
        String data1 = bf.readLine();
        Element em1 = document.createElement(element1);
        em1.appendChild(document.createTextNode(data1));
        rootElement.appendChild(em1);
  
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
          Transformer transformer = transformerFactory.newTransformer();
          DOMSource source = new DOMSource(document);
          StreamResult result =  new StreamResult(System.out);
          transformer.transform(source, result);
  
    }
  }
  </code></pre>
  
  <p>And it gives the following output:</p>
  
  <pre><code>run:
  Enter the Number: 768678
  Enter the SMS: ytu
  &lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt;&lt;SMS&gt;&lt;Number&gt;768678&lt;/Number&gt;&lt;message&gt;ytu&lt;/message&gt;&lt;/SMS&gt;BUILD SUCCESSFUL (total time: 8 seconds)
  </code></pre>
  
  <p>Now I want to write the generated output (<code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt;&lt;SMS&gt;&lt;Number&gt;768678&lt;/Number&gt;&lt;message&gt;ytu&lt;/message&gt;&lt;/SMS&gt;</code>) to a XML file on the hard disk. How do I do it?</p>