
HI,
I need a java program to create an xml file... therez a tutorial in your site to create an xml file at
http://www.roseindia.net/xml/dom/CreatXMLFile.shtml
but this isn't creating a file, its just displaying the output on console. I want an xml file abc.xml to be created with he program...
can you pls help...
Thanq in advance

Hi Friend,
Try the following code:
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class CreateXML{
public static void createXmlFile(Document doc,String name,String address,String contactNo,String email) throws Exception {
Element root = doc.createElement("Employee");
doc.appendChild(root);
Element element1 = doc.createElement("Emp_Name");
root.appendChild(element1);
Text text1 = doc.createTextNode(name);
element1.appendChild(text1);
Element element2 = doc.createElement("Emp_Address");
root.appendChild(element2);
Text text2 = doc.createTextNode(address);
element2.appendChild(text2);
Element element3 = doc.createElement("Emp_ContactNo");
root.appendChild(element3);
Text text3 = doc.createTextNode(contactNo);
element3.appendChild(text3);
Element element4 = doc.createElement("Email");
root.appendChild(element4);
Text text4 = doc.createTextNode(email);
element4.appendChild(text4);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = sw.toString();
File file = new File("c:/employee.xml");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
bw.write(xmlString);
bw.flush();
bw.close();
}
public static void main(String args[])throws Exception{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Scanner input=new Scanner(System.in);
System.out.print("Enter Employee Name:");
String name=input.nextLine();
System.out.print("Enter Address:");
String address=input.nextLine();
System.out.print("Enter Contact No:");
String contactNo=input.nextLine();
System.out.print("Enter Email:");
String email=input.nextLine();
createXmlFile(doc,name,address,contactNo,email);
System.out.println("Xml File is Created Successfully");
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.