Create - XML File (Document)

In this section, you will learn to create a XML document using the DOM APIs.

Create - XML File (Document)

Create - XML File (Document)

     

In this section, you will  learn to create a XML document using the DOM APIs. This XML document uses  1.0 version  and UTF-8 encoding. 

Description of program:

This program helps in creating a XML document on the console. This program asks for the number of elements to be added in the generated xml file. It takes the root name at the console and passes it in the createElement() method. It creates the Element object and invokes the Document object  . Depending upon the given number, it creates that much elements and fills them with data,. Finally, it displays the generated XML file with its version and encoding.

Here is the video insturction "How to create XML in Java?":

Here is Java File: CreatXMLFile.java

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[] argsthrows 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 = Integer.parseInt(str);
  System.out.print("Enter root: ");
  String root = bf.readLine();
  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();
  System.out.print("Enter the data: ");
  String data = bf.readLine();
  Element em = document.createElement(element);
  em.appendChild(document.createTextNode(data));
  rootElement.appendChild(em);
  }
  TransformerFactory transformerFactory = 
  TransformerFactory.newInstance
();
  Transformer transformer = transformerFactory.newTransformer();
  DOMSource source = new DOMSource(document);
  StreamResult result =  new StreamResult(System.out);
  transformer.transform(source, result);
  }
}

Download this example.

Output of this program:

C:\vinod\xml>javac CreatXMLFile.java

C:\vinod\xml>java CreatXMLFile
Enter number to add elements in your XML file: 3
Enter root: RonseIndia
Enter the element: Emp-Name
Enter the data: Vinod
Enter the element: Emp-Code
Enter the data: E-001
Enter the element: Emp-Desi
Enter the data: Junior-Programmer
<?xml version="1.0" encoding="UTF-8" standalone="no"?><RonseIndia>
<Emp-Name>Vino
d</Emp-Name><Emp-Code>E-001</Emp-Code>
<Emp-Desi>Junior-Programmer</Emp-Desi></Ro
nseIndia>

 

Download source code of the project in Eclipse Project format