Writing to a xml file in java

Posted by user243680 on Stack Overflow See other posts from Stack Overflow or by user243680
Published on 2010-03-16T09:08:50Z Indexed on 2010/03/16 9:16 UTC
Read the original article Hit count: 271

Filed under:
|
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 <= 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);

  }
}

i am working on the above code and it gives the following output

run:
Enter the Number: 768678
Enter the SMS: ytu
<?xml version="1.0" encoding="UTF-8" standalone="no"?><SMS><Number>768678</Number><message>ytu</message></SMS>BUILD SUCCESSFUL (total time: 8 seconds)

Now i want to write the output generated(<?xml version="1.0" encoding="UTF-8" standalone="no"?><SMS><Number>768678</Number><message>ytu</message></SMS>) to a XML file on the hard disk.How do i do it?

© Stack Overflow or respective owner

Related posts about java

Related posts about Xml