Pages

Ads 468x60px

Sunday, July 22, 2012

Java: Write XML file

Note: This program will create an XML file:-
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<SecurityQuestion>
   <question>question1</question>
   <question>question2</question>
   <question>question3</question>
</SecurityQuestion>



import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
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 {

    private String FILE_NAME = "SecurityQuestions.xml";
    private String root = "SecurityQuestion";
    private String element = "question";

    public void createXML() {
        FileWriter fstream = null;
        String[] questions = {"question1", "question2", "question3"};
        try {
         
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            Element rootElement = document.createElement(root);
            document.appendChild(rootElement);
         
     
                    for (int i=0; i<questions.length; i++) {              
                    Element em = document.createElement(element);
                    em.appendChild(document.createTextNode(questions[i]));
                    rootElement.appendChild(em);
                }
                 
                    TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    Transformer transformer = transformerFactory.newTransformer();
                    DOMSource source = new DOMSource(document);
                    fstream = new FileWriter(FILE_NAME);
                    StreamResult result = new StreamResult(fstream);
                    transformer.transform(source, result);
         
                     
         
        } catch (Exception ex) {
            ex.getMessage();
        }
    }

No comments:

Post a Comment