Writing Data in XML file Using JAVA
DOM provides many handy classes to create XML file easily. Firstly, you have to create a Document withDocumentBuilder class, define all the XML content – node, attribute with Element class. In last, use Transformer class to output the entire XML content to stream output, typically a File.
Download File: Click Here
Program:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.*;
import java.util.*;
public class xmlDemo{
public static void main(String []args){
// System.out.println("Hello World");
Scanner userinput=new Scanner(System.in);
try{
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=dbFactory.newDocumentBuilder();
Document doc=builder.newDocument();
Element rootElement=doc.createElement("Person");
doc.appendChild(rootElement);
for(int i=0;i<5;i++){
Element staff=doc.createElement("Staff");
rootElement.appendChild(staff);
System.out.print("Enter First Name:");
String fname=userinput.nextLine();
Element firstName=doc.createElement("FirstName");
firstName.appendChild(doc.createTextNode(fname));
staff.appendChild(firstName);
System.out.print("Enter Last Name:");
String lname=userinput.nextLine();
Element lastName=doc.createElement("lastName");
lastName.appendChild(doc.createTextNode(lname));
staff.appendChild(lastName);
System.out.print("Enter Salary:");
String usalary=userinput.nextLine();
Element salary=doc.createElement("Salary");
salary.appendChild(doc.createTextNode(usalary));
staff.appendChild(salary);
}
TransformerFactory transformerFactory =TransformerFactory.newInstance();
Transformer transformer =transformerFactory.newTransformer();
//Transformer.setOutputProperty(OutputKeys.INDENT,"yes");
DOMSource source = new DOMSource(doc);
StreamResult result =new StreamResult(new FileWriter("person.xml"));
transformer.transform(source, result);
System.out.println("Xml File Write Successfully....");
}catch(Exception ex){
System.out.println("Error: "+ex.getMessage());
}
}
}
How to Run:
(compilatin) $ javac xmlDemo.java
(run) $ java xmlDemo
No comments:
Post a Comment