JAVA XML

JavaXml Projects

JavaXml Project 1

JavaXml Examples

JavaXml EXAMPLE

Create XML Document
Previous Home Next

With help of this program, we will be learn to create a XML document using the DOM Application programming interfaces. In This XML document uses 1.0 version and UTF-8 encoding. By help of this program we can create 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.

Example

Here is Java File: Studentrecord.java

 

package r4r;
import org.w3c.dom.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
[an error occurred while processing this directive]
public class createxml {
	public static void main(String[] args) throws Exception {
		  BufferedReader br = new BufferedReader(
		  new InputStreamReader(System.in));
		System.out.print("Enter number to add elements in our XML file: ");
		  String str = br.readLine();
		  int nu = Integer.parseInt(str);
		  System.out.print("Enter root: ");
		  String root = br.readLine();
		  DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance();
		  DocumentBuilder docBuild = docFact.newDocumentBuilder();
		  Document docu = docBuild.newDocument();
		  Element rEle = docu.createElement(root);
		  docu.appendChild(rEle);
		  for (int i = 1; i <= nu; i++){
		  System.out.print("Enter the element: ");
		  String element = br.readLine();
		  System.out.print("Enter the data: ");
		  String data = br.readLine();
		  Element em = docu.createElement(element);
		  em.appendChild(docu.createTextNode(data));
		  rEle.appendChild(em);
		  }
		  TransformerFactory transFact = TransformerFactory.newInstance();
		  Transformer trans = transFact.newTransformer();
		  DOMSource dsrc = new DOMSource(docu);
		  StreamResult result =  new StreamResult(System.out);
		  trans.transform(dsrc, result);
		  }
}
Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: