You are on page 1of 62

Creating Blank DOM Document

This tutorial shows you how to create blank DOM document. JAXP (Java API for XML
Processing) is a Java interface that provides a standard approach to Parsing XML documents.
With JAXP, we will use the Document BuilderFactory to create DocumentBuilder class.

The class DocumentBuilderFactory is responsible for creating new DOM parsers. Normally it
is used to a DOM parser. Example is as follows:

 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();


 DocumentBuilder parser = factory.newDocumentBuilder();
 Document doc = parser.parse(myInputSource); //The parse function is used to
parse existing xml document.
 

DocumentBuilderFactory uses the system property


javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the
parser by calling:
 System.setProperty("javax.xml.parsers.XmlDocumentParserFactory",
                    "com.foo.myFactory");

The instance of the class DocumentBuilder is used to create a blank document. The
newDocument() method of the class returns a blank DOM document.

Document doc = parser.newDocument();

Here is the full code of CreateBlankDocument.java

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class CreateBlankDocument
{
    public static void main(String[] args)
    {
    System.out.println("Creating Balnk Document...");
    try{
    //Create instance of DocumentBuilderFactory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //Get the DocumentBuilder
    DocumentBuilder parser = factory.newDocumentBuilder();
    //Create blank DOM Document
        Document doc = parser.newDocument();
    }catch(Exception e){
      System.out.println(e.getMessage());
    }
    System.out.println("Done...");
    System.out.println("Exiting...");

  }

In the next section I will show you how to add root and child elements to the blank document.
Saving the DOM tree to the disk file is also discussed in the next secion.

Creating DOM Child Elements


This lesson shows you how to create root and child elements in the DOM tree. We will first
create a blank DOM document and add the root element to it. Then I show you how to add
comment element and then child element to the root element. In this example following xml code
will generated and displayed on the console.

<?xml version="1.0" encoding="UTF-8" ?> 


<root>
<!-- This is comment--> 
<Child attribute1="The value of Attribute
1" /> 
</root>

Creating the root element

In the previous lesson you learned how to create DocumentBuilder object and the create a blank
DOM document. The following code creates a blank document.

//Create blank DOM Document


Document doc = docBuilder.newDocument();

The createElement function is used to create the root element and appendChild method is used
to append the element to the DOM document.

//create the root element


Element root = doc.createElement("root");
//all it to the xml tree
doc.appendChild(root);

Adding Comment Element to DOM Tree

The doc.createComment function is used to create Comment object.

//create a comment
Comment comment = doc.createComment("This is comment");
//add in the root element
root.appendChild(comment);

Adding Child Element to DOM Tree

The doc.createElement function is used to create Child element.

//create child element


Element childElement = doc.createElement("Child");
//Add the atribute to the child
childElement.setAttribute("attribute1","The value of Attribute 1");
root.appendChild(childElement);

Printing the DOM Tree on console

An finally we will print the DOM tree on the console with the following code:

TransformerFactory tranFactory = TransformerFactory.newInstance(); 


Transformer aTransformer = tranFactory.newTransformer(); 

Source src = new DOMSource(doc); 


Result dest = new StreamResult(System.out); 
aTransformer.transform(src, dest); 

Here is the full code of CreateDomXml.java

import org.w3c.dom.*;

import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

class CreateDomXml 
{
  public static void main(String[] args) 
  {
    try{
    //Create instance of DocumentBuilderFactory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //Get the DocumentBuilder
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    //Create blank DOM Document
        Document doc = docBuilder.newDocument();

    //create the root element
        Element root = doc.createElement("root");
    //all it to the xml tree
        doc.appendChild(root);
    
      //create a comment
      Comment comment = doc.createComment("This is comment");
      //add in the root element
      root.appendChild(comment);

    //create child element
    Element childElement = doc.createElement("Child");
    //Add the atribute to the child
    childElement.setAttribute("attribute1","The value of Attribute 1");
    root.appendChild(childElement);
    

    TransformerFactory tranFactory = TransformerFactory.newInstance(); 
    Transformer aTransformer = tranFactory.newTransformer(); 

    Source src = new DOMSource(doc); 
    Result dest = new StreamResult(System.out); 
    aTransformer.transform(src, dest); 

    }catch(Exception e){
      System.out.println(e.getMessage());
    }

  }
}

Getting The XML Root Element


After reading this section, you will be able to retrieve a  root element from the XML
document.  The JAXP (Java APIs for XML Processing) provides a common interface for
creating and using xml files using the standard SAX, DOM and XSLTs. Here you will see
the given example to use DOM interface. 

Description of program:

You need a XML document (file). Both Java and the XML file are kept in the same directory.
This program takes a XML file as a String at the console . If the given file exists then it parses
the document using parse() method . Before parsing the XML document you need a
DocumentBuilder object. For creating this first of all you create a DocumentBuilderFactory.
After parsing the XML document you get  the node element using getDocumentElement()
method. To get the root element use the getNodeName() method.  

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: GetRootNode.java

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class GetRootNode{
  public static void main(String[] args) {
    try{
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter xml file name: ");
      String str = bf.readLine();
      File file = new File(str);
      if (file.exists()){
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = fact.newDocumentBuilder();
        Document doc = builder.parse(str);
        Node node = doc.getDocumentElement();
        String root = node.getNodeName();
        System.out.println("Root Node: " + root);
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch(Exception e){}
  }
}

Download this example.

Output of the program:

C:\vinod\xml>javac
GetRootNode.java

C:\vinod\xml>java
GetRootNode
Enter xml file name:
Employee-Detail.xml
Root Node: Employee-
Detail

To Count XML Element


In this section, you will learn to count the elements present in a  XML file using DOM APIs. 

Description of program:

This program helps to count the XML element. It takes a xml file (as a string ) at the console and
checks its availability. It parses the xml document using the parse() method. After parsing the
XML document it asks for element name which have to count.  Create a  NodeList and use the
getElementByTagName() method. The getLength() method counts the occurrences of the
specified element. If  the asked element is not available( i.e.. the given element isn't found) it
returns 0.

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: DOMCountElement.java

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class DOMCountElement{
    public static void main(String[] args) {
    try {
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter File name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // Create the builder and parse the file
        Document doc = factory.newDocumentBuilder().parse(xmlFile);
        System.out.print("Enter element name: ");
        String element = bf.readLine();
        NodeList nodes = doc.getElementsByTagName(element);
        System.out.println("xml Document Contains " + nodes.getLength() + "  e
lements.");
      }
      else{
        System.out.print("File not found!");
      }
    }
    catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

Download this example.

Output of program:

C:\vinod\xml>javac
DOMCountElement.java

C:\vinod\xml>java
DOMCountElement
Enter File name: Employee-
Detail.xml
Enter element name:
Emp_Name
xml Document Contains 3
elements.

In this section, you will learn to count the elements present in a  XML file using DOM APIs. 

Description of program:

This program helps to count the XML element. It takes a xml file (as a string ) at the console and
checks its availability. It parses the xml document using the parse() method. After parsing the
XML document it asks for element name which have to count.  Create a  NodeList and use the
getElementByTagName() method. The getLength() method counts the occurrences of the
specified element. If  the asked element is not available( i.e.. the given element isn't found) it
returns 0.

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: DOMCountElement.java

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class DOMCountElement{
    public static void main(String[] args) {
    try {
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter File name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // Create the builder and parse the file
        Document doc = factory.newDocumentBuilder().parse(xmlFile);
        System.out.print("Enter element name: ");
        String element = bf.readLine();
        NodeList nodes = doc.getElementsByTagName(element);
        System.out.println("xml Document Contains " + nodes.getLength() + "  e
lements.");
      }
      else{
        System.out.print("File not found!");
      }
    }
    catch (Exception ex) {
            System.out.println(ex);
        }
    }
}
Download this example.

Output of program:

C:\vinod\xml>javac
DOMCountElement.java

C:\vinod\xml>java
DOMCountElement
Enter File name: Employee-
Detail.xml
Enter element name:
Emp_Name
xml Document Contains 3
elements.

To Count The Elements in a XML File


In this section, you will learn to count the element in XML document using DOM APIs defined
in the org.apache.xerces.parsers.DOMParser  package. Your classpath must  contain 
xercesImpl.jar  and xml-apis.jar files  to run this program.
You can download it from Xerces

Description of program: This program takes a file name from the console and checks its
availability. If the file exists then  DOMParser is created  using the
org.apache.xerces.parsers.DOMParser package.This object parses the given XML document. It
asks the element name and counts its occurence in the xml file. If the given element doesn't exist
it displays the '0' element.

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: CountNodes.java

import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
import java.io.*;

public class CountNodes{
  public static void main(String[] args) {
    try{
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter file name: ");
      String str = bf.readLine();
      File file = new File(str);
      if (file.exists()){
        DOMParser parser = new DOMParser();
        parser.parse(str);
        Document doc = parser.getDocument();
        System.out.print("Enter element that have to count: ");
        String ele = bf.readLine();
        NodeList list = doc.getElementsByTagName(ele);
        System.out.println("Number of nodes: " + list.getLength());
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      e.getMessage();
    }
  }
}

Download this example.


Output of program:

C:\vinod\xml>javac
CountNodes.java

C:\vinod\xml>java
CountNodes
Enter file name: Employee-
Detail.xml
Enter element that have to
count: Emp_Name
Number of nodes: 3

XML Well-Formed-ness
In this section, you will learn to check the well-formed-ness  of a XML using the DOM
interface. A  well-formed  XML  document must follow the xml syntax rules.

Description of program:

For checking the "well-formedness" of  a XML document you should use the given example.
The DOM parser parsers (parse()) the XML document using the DocumentBuilder and
DocumentBuilderFactory. Whenever the XML document is well-formed, it shows a message
"Employee-Detail.xml is well-formed". Otherwise it displays "Employee-Detail.xml isn't well-
formed.". 

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: DOMParserCheck.java

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

public class DOMParserCheck {
  static public void main(String[] arg){
    try{
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter File name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if(file.exists()){
        try {
          // Create a new factory to create parsers 
          DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
          // Use the factory to create a parser (builder) and use
          // it to parse the document.
          DocumentBuilder builder = dBF.newDocumentBuilder();
          // builder.setErrorHandler(new MyErrorHandler());
          InputSource is = new InputSource(xmlFile);
          Document doc = builder.parse(is);
          System.out.println(xmlFile + " is well-formed!");
        }
        catch (Exception e) {
          System.out.println(xmlFile + " isn't well-formed!");
          System.exit(1);
        }
      }
      else{
        System.out.print("File not found!");
      }
    }
    catch(IOException io){
      io.printStackTrace();
    }
  }
}

Download this example.

Output of program:

C:\vinod\xml>javac
DOMParserCheck.java

C:\vinod\xml>java
DOMParserCheck
Enter File name: Employee-
Detail.xml
Employee-Detail.xml is
well-formed!

Searching an Element in the given XML


Document
In this you will learn to search an element in the specified XML document using DOM APIs
defined in the org.apache.xerces.parsers.DOMParser  package. Your classpath must  contain 
xercesImpl.jar  and xml-apis.jar files  to run this program.
You can download it from Xerces

Description of program:

This program asks for a  XML file name and checks it existence. If the given file exists then it
parses  the file using the parse() method. This method parses the XML document with the help of
DOMParser. The DOMParser is defined in the org.apache.xerces.parsers.DOMParser. It is
very useful for to create the DOMParser object. This program asks for a  xml element name that
have to be searched in the XML document. Use the getLength() method for counting the
occurrences of a given element  in XML document. If it counts to '0' that means element doesn't
found and it displays "Element doesn't exist in the Employee-Detail.xml Document." Else it
counts a given element 

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: SearchElement.java

import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
import java.io.*;

public class SearchElement{
  public static void main(String[] args) {
    try{
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter file name: ");
      String str = bf.readLine();
      File file = new File(str);
      if (file.exists()){
        DOMParser parser = new DOMParser();
        parser.parse(str);
        Document doc = parser.getDocument();
        System.out.print("Enter element that have to count: ");
        String ele = bf.readLine();
        NodeList list = doc.getElementsByTagName(ele);
        if(list.getLength() == 0){
          System.out.println("Element doesn't exist in the " + str + " Documen
t.");
        }
        else{
          System.out.println("Element occurrs " + list.getLength() + " times i
n the " + str);
        }
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      e.getMessage();
    }
  }
}

Download this example.

Output of program:

C:\vinod\xml>javac
SearchElement.java

C:\vinod\xml>java SearchElement
Enter file name: Employee- Create - XML File
Detail.xml
Enter element that have to count: (Document)
Emp_name
Element doesn't exist in the In this section, you will  learn to create a XML
Employee-Detail.xml Document. document using the DOM APIs. This XML document
uses  1.0 version  and UTF-8 encoding. 
C:\vinod\xml>java SearchElement
Enter file name: Employee- Description of program:
Detail.xml
Enter element that have to count: This program helps in creating a XML document on the
Emp_Name console. This program asks for the number of elements
Element occurrs 3 times in the to be added in the generated xml file. It takes the root
Employee-Detail.xml 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 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[] args) throws 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>

Regenerating XML  file


In this section, you will learn to get the  elements and its value using DOM APIs. 

Description of program:

This example parses a xml file and regenerates it at the console using the DOM APIs. This
program takes a XML file and initially checks its availability . If file exists then it creates
DocumentBuilderFactory. This object creates a DocumentBuilder which parses the XML
document using the parse() method. It invokes the DocumentBuilder object and creates a
Document object. Through this object you create DOM tree nodes by using the
getDocumentElement() method and passes it to the DOMSource(). The DOMSource
constructor creates a new input source with a DOM node. And the destination source (where you
recieve the result) uses the StreamResult() constructor. Here the "System.out" shows the  result
on the console. 

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: GetElementsDOM.java

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.*; 
import javax.xml.transform.stream.*;

public class GetElementsDOM{
  static public void main(String[] arg)throws Exception{
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter XML File Name: ");
    String xmlFile = bf.readLine();
    File file = new File(xmlFile);
    if(file.exists()){
      try {
        // Create a factory 
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // Use document builder factory
        DocumentBuilder builder = factory.newDocumentBuilder();
        //Parse the document
        Document doc = builder.parse(xmlFile); 
        TransformerFactory tranFact = TransformerFactory.newInstance(); 
        Transformer transfor = tranFact.newTransformer(); 
        Node node =doc.getDocumentElement();
        Source src = new DOMSource(node); 
        Result dest = new StreamResult(System.out);
        transfor.transform(src, dest);
      }
      catch (Exception e) {
        System.err.println(e);
      }
    }
    else{
      System.out.print("File not found!");
    }
  }
}

Download this example.

Output of this program:

C:\vinod\xml>javac
GetElementsDOM.java

C:\vinod\xml>java GetElementsDOM
Enter XML File Name: Employee-
Detail.xml
<?xml version="1.0" encoding="UTF-
8"?><Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit </Emp_Name>
<Emp_E-mail> Amit2@gmail.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@hotmail.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

XML Error checker and locater (DOM)


In this section, you will learn to check and locate (line and column number) an error in your
XML document using the DOM APIs.  The XML document follows some rules to check its
syntax. 
Description of program:

This program takes a XML file on the console and it checks whether the given file exists or not.
If it exists then it parses the file using the parse() method. DocumentBuilderFactory and
DocumentBuilder classes are needed to get a dom parser. All the  parsers have inbuilt capability
to verify the well-formed ness of a xml file . No you need not to add any extra method for
checking wellformed ness .If the xml file is wellformed , the parsing of the xml document get
successfully completed , and the program displays a message like "Employee-Detail.xml is well-
formed!". Otherwise, it displays an error and exact error location (line and column number). 

Here is the XML File: Employee-Detail1.xml

<?xml version = "1.0" ?>


<Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee
</Employee-Detail>

Here is the Java File: DOMLocateError.java

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

public class DOMLocateError{
  static public void main(String[] arg){
    try {
      BufferedReader bf = new BufferedReader(new
                                   InputStreamReader(System.in));
      System.out.print("Enter File name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if(file.exists()){
        // Create a new factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // Use the factory to create builder document.
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        System.out.println(xmlFile + " is well-formed!");
      }
      else{
        System.out.print("File not found!");
      }
    }
    catch (SAXParseException e) {
      System.out.println("type" + ": " + e.getMessage()+"\n");
      System.out.println("Line " + e.getLineNumber() + " Column "
                                               + e.getColumnNumber());
    }
    catch (SAXException e) {
      System.err.println(e);
      System.exit(1);
    }
    catch (ParserConfigurationException e) {
      System.err.println(e);
      System.exit(1);
    }
    catch (IOException e) {
      System.err.println(e);
      System.exit(1);
    }
  }
}

Download this example. 

Output of this program:

C:\vinod\xml>javac DOMLocateError.java

C:\vinod\xml>java DOMLocateError
Enter File name: Employee-Detail1.xml
[Fatal Error] Employee-Detail1.xml:9:1: The end-
tag for element type "Employee"
must end with a '>' delimiter.
type: The end-tag for element type "Employee"
must end with a '>' delimiter.

Line 9 Column 1

Getting all XML Elements


In this section, you will learn to retrieve all elements of the XML file using the DOM APIs. This
APIs provides some constructors and methods which helps us to parse the XML file and retrieve
all elements.

Description of program:

The following program helps you in getting all XML elements displayed on the console. This
program asks for a XML file name and checks its availability. whether the given file exists or not
in the same directory. So, you need a XML file (Employee-Detail.xml) that contains some
elements. Program parses the xml file using the parse() method and creates a Document object
Tree.  DocumentBuilder object  helps you to get features to parse the XML file.  After parsing
the XML file a NodeList is created using the getElementsByTagName().This NodeList object
creates element.  Elements name are retrieved using the getNodeName() method. 

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is Java File: DOMElements.java

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

public class DOMElements{
   static public void main(String[] arg){
     try {
       BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)
);
       System.out.print("Enter XML File name: ");
       String xmlFile = bf.readLine();
       File file = new File(xmlFile);
       if(file.exists()){
         // Create a factory
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance()
;
         // Use the factory to create a builder
         DocumentBuilder builder = factory.newDocumentBuilder();
         Document doc = builder.parse(xmlFile);
         // Get a list of all elements in the document
         NodeList list = doc.getElementsByTagName("*");
         System.out.println("XML Elements: ");
         for (int i=0; i<list.getLength(); i++) {
           // Get element
           Element element = (Element)list.item(i);
           System.out.println(element.getNodeName());
         }
       }
       else{
         System.out.print("File not found!");
       }
     }
     catch (Exception e) {
       System.exit(1);
     }
   }
}

Download this example.

Output of this program:

C:\vinod\xml>javac
DOMElements.java

C:\vinod\xml>java
DOMElements
Enter XML File name:
Employee-Detail.xml
XML Elements:
Employee-Detail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail

Adding DOCTYPE to a  XML File


In this section, you will learn to add a DOCTYPE to your XML file  using the DOM APIs. 

Description of program:

The following program helps to add a  DOCTYPE in your XML  file. Program takes a XML file
name on the console and it checks, the given file exists or not. If the given file exists then it is 
parsed using the parse() method and a Document object treee is created . Abstract class
Transformer is used to transform a source tree into a xml file The setOutputProperty() method
invokes to the Transformer object and sets the systemId and publicId to the  DOCTYPE in the
XML file. 

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: AddDocType.java

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class AddDocType{
  static public void main(String[] args){
    try{
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter XML file name: ");
      String xmlFile = bf.readLine();
      System.out.println();
      File file = new File(xmlFile);
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
//        Create transformer
        Transformer tFormer = TransformerFactory.newInstance().newTransformer(
);
//        Set system id
        tFormer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "systmId");
//        Set public id
//        tFormer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "publicId");
        Source source = new DOMSource(doc);
        Result result = new StreamResult(System.out);
        tFormer.transform(source, result);
        System.out.println();
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      e.getMessage();
    }
  }
}

Download this example.

Output of this program:


XML docType SystemId and publicId

C:\vinod\xml>java AddDocType
Enter XML file name: Employee-Detail.xml

<?xml version="1.0" encoding="UTF-8"


standalone="no"?><!DOCTYPE Employee-Detail
PUBLIC "publicId" "systmId">
<Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail>
</Employee>
<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Sushil </Emp_Name>
<Emp_E-mail>Sushil@yahoo.com </Emp_E-mail>
</Employee>
<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Amit </Emp_Name>
<Emp_E-mail> Amit@yahoo.com </Emp_E-mail>
</Employee>
</Employee-Detail>

Getting Dom Tree Elements and their


Corresponding XML Fragments
In this section, you will learn to get the elements of a DOM tree and their corresponding XML
fragments. Each element of dom tree has a node level starting with '0'. Here the DOM tree
elements and their corresponding XML fragments are displayed on the console.

Description of the program:

This program helps you to retrieve the  elements of a DOM tree  and their corresponding XML
fragments on the console. To parse the xml file you need the DocumentBuilder and
DoucnemtBuilderFactory.  With the help of this you create a NodeList through the
getElementByTagName() method. The NodeList helps you in getting the length and Element.
For getting the node name you use the getNodeName() method. The transform() method
displays the data source and the given destination. This program uses the "System.out" to
display the data on the console. 

Here is the XML File: Employee-Detail2.xml


<?xml version = "1.0" ?>
<Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>
</Employee-Detail>

Here is the Java File: DisplayElementNodes.java

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class DisplayElementNodes {
  static public void main(String[] arg){
    try{
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter a XML file name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        TransformerFactory tranFactory = TransformerFactory.newInstance(); 
        Transformer aTransformer = tranFactory.newTransformer(); 
        // Get nodes list of all elements
        NodeList list = doc.getElementsByTagName("*");
        for (int i=0; i<list.getLength(); i++){
          // Get element
          Element element = (Element)list.item(i);
          Source src = new DOMSource(element); 
          System.out.println("Node no: " + i + " is " + element.getNodeName())
;
          System.out.println( "Its corresponding xml representation:");
          Result dest = new StreamResult(System.out);
          aTransformer.transform(src, dest);
          System.out.println("\n");
        }
      }
      else{
        System.out.println(xmlFile + " (file name) doesn't found!");
      }
    }
    catch (Exception e){
      e.getMessage();
    }
  }
}

Download this example.

Output of this program:

C:\vinod\xml>javac DisplayElementNodes.java

C:\vinod\xml>java DisplayElementNodes
Enter a XML file name: Employee-Detail2.xml
Node no: 0 is Employee-Detail
Its corresponding xml representation:
<?xml version="1.0" encoding="UTF-8"?><Employee-
Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail>
</Employee>

</Employee-Detail>

Node no: 1 is Employee


Its corresponding xml representation:
<?xml version="1.0" encoding="UTF-8"?><Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail>
</Employee>

Node no: 2 is Emp_Id


Its corresponding xml representation:
<?xml version="1.0" encoding="UTF-8"?><Emp_Id> E-
001 </Emp_Id>

Node no: 3 is Emp_Name


Its corresponding xml representation:
<?xml version="1.0" encoding="UTF-8"?><Emp_Name>
Vinod </Emp_Name>

Node no: 4 is Emp_E-mail


Its corresponding xml representation:
<?xml version="1.0" encoding="UTF-8"?><Emp_E-mail>
Vinod1@yahoo.com </Emp_E-mail>

Cloning a XML Element


In this section, you will learn to create a clone of a  element in the DOM tree. In general, the
cloning means to create a duplicate. 

Description of a program:

The following program helps you in creating a clone of any element of the specified XML file.
For creating a DOM object ,  you need the  DocumentBuilderFactoty and the
DocumentBuilder objects. After parsing it displays a xml file on the console using the
transform() method. At  run time the program asks for a  element name to clone . Here the
element1.cloneNode(true) method creates a clone and
element1.getParentNode().insertBefore(copyElement, element1.getNextSibling()) inserts the clone
element at the specified position.

Here is the XML File: Employee-Detail2.xml

<?xml version = "1.0" ?>


<Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>
</Employee-Detail>

Here is the Java File: DOMCloneElements.java

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class DOMCloneElements {
  static public void main(String[] arg){
    try  {
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter XML file name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tformer = tFactory.newTransformer();
        Source source = new DOMSource(doc);
        Result result = new StreamResult(System.out);
        System.out.println(xmlFile + " file: ");
        tformer.transform(source, result);
        System.out.println();
        System.out.print("Enter the element to clone: ");
        String clone = bf.readLine();
        System.out.print("Enter data to add: ");
        String addElement = bf.readLine();
        ////////////////////////////////
        NodeList list = doc.getElementsByTagName(clone);
        Element element1 = (Element)list.item(0);
        Element copyElement = (Element) element1.cloneNode(true);
        element1.getParentNode().insertBefore(copyElement, 
                                  element1.getNextSibling());
        element1.appendChild(doc.createTextNode(addElement));
        tformer.transform(source, result);
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      e.getMessage();
    }
  }
}

Download this example.

 Output of this program:

C:\vinod\xml>javac DOMCloneElements.java

C:\vinod\xml>java DOMCloneElements
Enter XML file name: Employee-Detail2.xml
Employee-Detail2.xml file:
<?xml version="1.0" encoding="UTF-8"
standalone="no"?><Employee-Detail>
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </Emp_E-
mail>
</Employee>
</Employee-Detail>
Enter the element to clone: Emp_Id
Enter data to add: E011
<?xml version="1.0" encoding="UTF-8"
standalone="no"?><Employee-Detail>
<Employee>
<Emp_Id> E-001 E011</Emp_Id><Emp_Id> E-
001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </Emp_E-
mail>
</Employee>
</Employee-Detail>

Remove Element from XML Document


In this section, you will learn to remove any element from a given  XML document. Whenever
you remove the xml element from the xml document the data are also lost from the xml element.

Description of program:

This program takes a XML file name on the console. At the run time the program asks for an
element name to be deleted. The removeChild() method  removes the given element from the
XML document by  invoking the getParentNode() method .

Here is the XML File:E-mail.xml

<?xml version="1.0"?>
<E-mail>
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</S
ubject>
<Body>Be ready for a
cruise...</Body>
</E-mail>

Here is the Java File: RemoveElement.java

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class RemoveElement {
  static public void main(String[] arg) {
    try{
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter a XML file name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      System.out.print("Enter an element which have to delete: ");
      String remElement = bf.readLine();
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer = tFactory.newTransformer();
        Element element = (Element)doc.getElementsByTagName(remElement).item(0
);
//        Remove the node
        element.getParentNode().removeChild(element);
//              Normalize the DOM tree to combine all adjacent nodes
        doc.normalize();
        Source source = new DOMSource(doc);
        Result dest = new StreamResult(System.out);
        tFormer.transform(source, dest);
        System.out.println();
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      System.err.println(e);
      System.exit(0);
    }
  }
}

Download this example.

Output of this program:

C:\vinod\xml>javac RemoveElement.java

C:\vinod\xml>java RemoveElement
Enter a XML file name: E-mail.xml
Enter an element which have to delete:
Subject
<?xml version="1.0" encoding="UTF-8"
standalone="no"?><E-mail>
<To>Rohan</To>
<From>Amit</From>

<Body>Be ready for a cruise...</Body>


</E-mail>

Getting Data from XML File (Document)


In this section, you will learn to retrieve the data from a XML file. All xml files store the data.
You can add and modify the data in the  xml document using the DOM APIs.

Description of program:

This program helps you in retrieving the data from a XML file. It takes a xml file on the console
with a message "Enter xml file name: ". After getting the xml file it parses. To parse you need
DocumentBuilderFactory and DocumentBuilder. Then we create a Transformer. The
setOutputProperty() is an abstract method of javax.xml.transform package which invokes the
Transformer object and sets an output property.  In setOutputProperty() method we set the
property "text" to generate the output in  the text format only.

An object of Document type is passed in the DOMSource() constructor. Finally, we create a


Result  type object needed to generate the result. The transform() method takes the Source and
Result objects and it processes the source tree to the output . Here the results are displayed at the
console from the XML document.

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Sushil
</Emp_Name>
<Emp_E-
mail>Sushil@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail>
Amit@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: GetData.java

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class GetData{
  static public void main(String[] arg) {
    try{
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter XML file name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
//        Create transformer
        Transformer tFormer = TransformerFactory.newInstance().newTransformer(
);
//        Output text type
        tFormer.setOutputProperty(OutputKeys.METHOD, "text");
//        Write the document to a file
        Source source = new DOMSource(doc);
        Result result = new StreamResult(System.out);
        tFormer.transform(source, result);
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      System.err.println(e);
      System.exit(0);
    }  
  }
}

Download this example.

Output of this program:

C:\vinod\xml>javac
GetData.java

C:\vinod\xml>java
GetData
Enter XML file name:
Employee-Detail.xml

       E-001
       Vinod
       Vinod1@yahoo.com

       E-002
       Sushil
       Sushil@yahoo.com

       E-003
       Amit
       Amit@yahoo.com

Storing Data (Retrieved from a XML


Document) to a File
In this section, you will learn to store data (retrieved from the XML document) to a specified file
(with  extension '.txt', '.doc', '.xls', '.shtml' etc.) in different formats (text, xml, html etc.). 

Description of program:

This is a very simple program that helps you in storing the data to a specified file in different
format. After running this program asks you a xml file name at the console. If the given file
exists it parses and creates a Document object . To parse it you need the
DocumentBuilderFactory and DocumentBuilder object. We create a Transformer and use the
setOutputProperty() method that is an abstract method to invoke the Transformer object and
sets an output property that will generate a output in desired format. In this method you set the
"text" value for generating the text retrieved from the xml document. 
An object of Document is passed in the DOMSource() constructor . Result object is created to
show the generated file as output. Here we give a file name with extension, it creates a new file
according to given file name and extension. The transform() method takes the Source and
Result objects and it processes the source object to the output result. When the file is created it
displays a message "File creation successfully!" Here the results are displayed in different files
like: vk.txt, vk.doc, vk.xls, vk.shtml etc. from the XML document.

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Sushil
</Emp_Name>
<Emp_E-
mail>Sushil@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail>
Amit@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: StoreData.java

import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;

public class StoreData{
  static public void main(String[] arg) {
    try{
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter XML file name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if (file.exists()){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
//        Create transformer
        Transformer tFormer = TransformerFactory.newInstance().newTransformer(
);
//        Output Types (text/xml/html)
        tFormer.setOutputProperty(OutputKeys.METHOD, "text");
//        Write the document to a file
        Source source = new DOMSource(doc);
//       Create File  to view your xml data as      
vk.txt/vk.doc/vk.xls/vk.shtml/vk.html)
        Result result = new StreamResult(new File("vk.txt"));
        tFormer.transform(source, result);
        System.out.println("File creation successfully!");
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      System.err.println(e);
      System.exit(0);
    }  
  }
}

Download this example.

Output of program:

C:\vinod\xml>javac
StoreData.java

C:\vinod\xml>java
StoreData
Enter XML file name:
Employee-Detail.xml
File creation successfully!
C:\vinod\xml>

XML Validate DTD


In this section, you will learn to validate a xml file against a  DTD (Document Type Definition) 
using the DOM APIs. A DTD defines  the document structure with a list of legal elements and
attributes.

Description of program:

Validating a XML file against a DTD needs a xml file and its DTD document. First of all
construct a well-formed xml file along with a DTD file . This DTD file defines all elements to
keep in the xml file. After creating these, we parse the xml file using the parse() method and
generates a Document object tree. The setErrorHandler() method invokes an object of
DoucmentBuilder. Enable the setValidating() method of the factory to "true".  If we pass 'true'
the parser will validate xml documents otherwise not. To validate xml file , pass the DTD file as
setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "Employee.dtd") in the transformer
object.

Here is the xml file: Employeexy.xml

<?xml version = "1.0" ?>


<!DOCTYPE Employee SYSTEM
"Employee.dtd">
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

Here is the DTD File: Employee.dtd

<!ELEMENT Employee (Emp_Id,


Emp_Name, Emp_E-mail)>
<!ELEMENT Emp_Id (#PCDATA)>
<!ELEMENT Emp_Name
(#PCDATA)>
<!ELEMENT Emp_E-mail
(#PCDATA)>

Here is the Java file: DOMValidateDTD.java


import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.validation.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;

public class DOMValidateDTD {
  public static void main(String args[]) {  
    try{
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(true);
      DocumentBuilder builder = factory.newDocumentBuilder();
      builder.setErrorHandler(new org.xml.sax.ErrorHandler() {
        //Ignore the fatal errors
        public void fatalError(SAXParseException exception)throws SAXException 
{ }
        //Validation errors 
        public void error(SAXParseException e)throws SAXParseException {
          System.out.println("Error at " +e.getLineNumber() + " line.");
          System.out.println(e.getMessage());
          System.exit(0);
        }
        //Show warnings
        public void warning(SAXParseException err)throws SAXParseException{
          System.out.println(err.getMessage());
          System.exit(0);
        }
      });
      Document xmlDocument = builder.parse(new FileInputStream("Employeexy.xml
"));
      DOMSource source = new DOMSource(xmlDocument);
      StreamResult result = new StreamResult(System.out);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "Employee.dtd")
;
      transformer.transform(source, result);
    }
    catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}

Download this example.

Output of this program:

C:\vinod\xml>javac DOMValidateDTD.java
C:\vinod\xml>java DOMValidateDTD
<?xml version="1.0" encoding="UTF-8" standalone="no"?
><!DOCTYPE Employee SYSTEM
"Employee.dtd">
<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail>

Accessing XML file from Java


This section is going to tell you how to access a XML file using Java Code.

In this example we have provided you a simple java example with the source code that will make
it possible to access the XML file through Java. For that we have used DOM parser. DOM parser
that loads the XML file into the memory and makes an object model which can be traversed to
get the file elements. For this, we have created two different files:
1) MyFile.xml
2) AccessingXmlFile.java

Source Code for accessing XML file through Java

File MyFile.xml

<?xml version="1.0"?
>
<student>
<student-name>
<firstname>Anusmita<
/firstname>
<lastname>Singh</last
name>
</student-name>

<student-address>
<address>Rohini</add
ress>
<city>Delhi</city>
</student-address>
</student>
[an error occurred while processing this directive]

Here is the code of AccessingXmlFile.javah

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;

public class AccessingXmlFile {

 public static void main(String argv[]) {

  try {
  File file = new File("C:\\MyFile.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newIns
tance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document document = db.parse(file);
  document.getDocumentElement().normalize();
  System.out.println("Root element "+document.getDocumentEle
ment().getNodeName());
  NodeList node = document.getElementsByTagName("student");
  System.out.println("Information of the students");

  for (int i = 0; i < node.getLength(); i++) {
  Node firstNode = node.item(i);
    
  if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
  
  Element element = (Element) firstNode;
  NodeList firstNameElemntList = element.getElementsByTagNam
e("firstname");
  Element firstNameElement = (Element) firstNameElemntList.i
tem(0);
  NodeList firstName = firstNameElement.getChildNodes();
  System.out.println("First Name:"+ ((Node)firstName.item(0)
.getNodeValue());
      
  NodeList lastNameElementList = element.getElementsByTagNam
e("lastname");
  Element lastNameElement = (Element) lastNameElementList.it
em(0);
  NodeList lastName = lastNameElement.getChildNodes();
  System.out.println("Last Name :"+
((Node)lastName.item(0).getNodeValue());

  NodeList addressList = element.getElementsByTagName("addre
ss");
  Element addressElement = (Element) addressList.item(0);
  NodeList address = addressElement.getChildNodes();
  System.out.println("Address : "  + ((Node) address.item(0)
).getNodeValue());
  NodeList cityList = element.getElementsByTagName("city");
  Element cityElement = (Element) cityList.item(0);
  NodeList city = cityElement.getChildNodes();
  System.out.println("City : "  + ((Node) city.item(0)).getN
odeValue());
 }
}
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
}

In the above example, the method DocumentBuilderFactory.newInstance() enables


applications to obtain a parser that produces DOM. The DocumentBuilder provides the DOM
document instances from XML document. The Document refers to the HTML or XML
document. The getDocumentElement() method provides the XML root Element. The
getElementsByTag Name() provides the tag. Then get the value of node by getNodeValue().

Following output will be displayed on the console:

XML Well-Formed Verifier


In this section we are going to develop a simple java program that determines whether a  XML
document is well-formed or not.

Description of the program:

In the following program, you will learn to parse a xml document and determine whether it is
well-formed or not.                                                                      Develop a java file
(SAXParserCheck.java) that uses a  xml file to parse and check its well-formedness. Initially
the program checks that the given file exists or not by using exists() method. If the file exists
then it will parse the xml file with the help of parse() method.

The XMLReaderFactory helps in creating an XML reader which parses  xml document using the
appropriate callbacks. And it determines that the parsed xml is well-formed or not. If xml
document is will-formed, it will display a message "Employee-Detail.xml is well-formed!"
Otherwise prints "Employee-Detail.xml isn't well-formed!". If you enter a  file that doesn't exist
it will show "File not found: Employee-Detail.xml".
Here is the XML File to be parsed: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the code of Java File: SAXParserCheck.java

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;

public class SAXParserCheck{

  public static void main(String[] args) throws IOException{
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter XML file name:");
    String xmlFile = bf.readLine();
    SAXParserCheck par = new SAXParserCheck(xmlFile);
  }
  
  public SAXParserCheck(String str){
    try{
      File file = new File(str);
      if (file.exists()){
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.parse(str);
        System.out.println(str + " is well-formed!");
      }
      else{
        System.out.println("File not found: " + str);
      }
    }
    catch (SAXException sax){
      System.out.println(str + " isn't well-formed");
    }
    catch (IOException io){
      System.out.println(io.getMessage());
    }
  }
}

Download this example 

Output of program:

C:\vinod\xml\comXML>javac
SAXParserCheck.java

C:\vinod\xml\comXML>java
SAXParserCheck
Enter XML file
name:Employee-Detail.xml
Employee-Detail.xml is well-
formed!

Get In this section you will learn to develop a simple java program to get the names of all
elements contained in the XML document .

Description of the program:

The following program teaches to parse the elements and retrieve  their names, from a  XML
document.                                                                              

Create a java file to retrieve the starting elements. When you run this program it asks for a XML
document. This is used as a command line argument. If  you don't enter any file, the program
throws an exception displaying "java.lang.ArrayIndexOutOfBoundsException: 0 at
XMLElements.main( XML Elements.java:17)". 

The parse() method of SAXParser class reads the contents. The SAXParserFactory  is a
factory API that enables applications to configure and obtain a SAX  parser to parse XML
documents. The startElement() method retrieves all starting elements and prints them on the
console. Whenever an error  occurs  it throws the SAXException.  

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: XMLElements.java

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class XMLElements{
  public static void main(String[] args) {
    try{
      SAXParserFactory parserFact = SAXParserFactory.newInstance();
      SAXParser parser = parserFact.newSAXParser();
      System.out.println("XML Elements: ");
      DefaultHandler handler = new DefaultHandler(){
        public void startElement(String uri, String lName, 
            String ele, Attributes attributes)throws SAXException{
          //print elements of xml
          System.out.println(ele);
        }
      };
      parser.parse(args[0], handler);
    }
    catch (Exception e){
      e.printStackTrace();
    }
  }
}

Download this example 

Output of program:

C:\vinod\xml\comXML>javac
XMLElements.java

C:\vinod\xml\comXML>java
XMLElements Employee-Detail.xml
XML Elements:
Employee-Detail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail

Get XML Elements


In this section you will learn to develop a simple java program to get the names of all
elements contained in the XML document .

Description of the program:

The following program teaches to parse the elements and retrieve  their names, from a  XML
document.                                                                              
Create a java file to retrieve the starting elements. When you run this program it asks for a XML
document. This is used as a command line argument. If  you don't enter any file, the program
throws an exception displaying "java.lang.ArrayIndexOutOfBoundsException: 0 at
XMLElements.main( XML Elements.java:17)". 

The parse() method of SAXParser class reads the contents. The SAXParserFactory  is a
factory API that enables applications to configure and obtain a SAX  parser to parse XML
documents. The startElement() method retrieves all starting elements and prints them on the
console. Whenever an error  occurs  it throws the SAXException.  

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: XMLElements.java

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class XMLElements{
  public static void main(String[] args) {
    try{
      SAXParserFactory parserFact = SAXParserFactory.newInstance();
      SAXParser parser = parserFact.newSAXParser();
      System.out.println("XML Elements: ");
      DefaultHandler handler = new DefaultHandler(){
        public void startElement(String uri, String lName, 
            String ele, Attributes attributes)throws SAXException{
          //print elements of xml
          System.out.println(ele);
        }
      };
      parser.parse(args[0], handler);
    }
    catch (Exception e){
      e.printStackTrace();
    }
  }
}

Download this example 

Output of program:

C:\vinod\xml\comXML>javac
XMLElements.java

C:\vinod\xml\comXML>java
XMLElements Employee-Detail.xml
XML Elements:
Employee-Detail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail

Get Data From the XML File


Here you will learn to retrieve data from XML file using SAX parser. We use the JAXP APIs to
retrieve data from XML document .

Description of program:

In this example you need a well-formed XML file that has some data (Emp_Id, Emp_Name and
Emp_E-mail in our case). Create a java program (EmployeeDetails.java) that retrieves data
from it. When you run the program it asks for a file with a message "Enter XML file name:" at
the command line and checks its existence through exists() method. If the given file exits, the
instance of SAXParser class parses the file  using the parse() method.                   Till  the
startElement() method returns 'true', the characters() method prints data . If  the file doesn't
exist it will display a message "File not found!". 

Characters(char[] ch, int start, int len)  method retrieves identification of character data. The
Parser calls this method and to report every character data encountered . If any error occurs it
throws the SAXException. This method takes the following parameters: 

        ch: This is the characters of XML document.


        start: This is staring position in an array.
        len: This is the number of characters to read from an array.  

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: EmployeeDetails.java

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;

public class EmployeeDetails{
  public static void main(String[] args) throws IOException{
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter XML file name:");
    String xmlFile = bf.readLine();
    EmployeeDetails detail = new EmployeeDetails(xmlFile);
  }
  public EmployeeDetails(String str){
    try{
      File file = new File(str);
      if (file.exists()){
        SAXParserFactory parserFact = SAXParserFactory.newInstance();
        SAXParser parser = parserFact.newSAXParser();
        System.out.println("XML Data: ");
        DefaultHandler dHandler = new DefaultHandler(){
          
          boolean id;
          boolean name;
          boolean mail;
          
          public void startElement(String uri, String localName, 
           String element_name, Attributes attributes)throws SAXException{
            if (element_name.equals("Emp_Id")){
              id = true;
            }
            if (element_name.equals("Emp_Name")){
              name = true;
            }
            if (element_name.equals("Emp_E-mail")){
              mail = true;
            }
          }
          
          public void characters(char[] ch, int start, int len) throws SAXExce
ption{
            String str = new String (ch, start, len);
            if (id){
              System.out.println("Emp_Id: "+str);
              id = false;
            }
            if (name){
              System.out.println("Name:   "+str);
              name = false;
            }
            if (mail){
              System.out.println("E-mail: "+str);
              mail = false;
            }
          }
        };
        
        parser.parse(str, dHandler);
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e){
      System.out.println("XML File hasn't any elements");
      e.printStackTrace();
    }
  }
}

Download this example

Output of program:

C:\vinod\xml\comXML>javac
EmployeeDetails.java

C:\vinod\xml\comXML>java
EmployeeDetails
Enter XML file name:Employee-
Detail.xml
XML Data:
Emp_Id: E-001
Name: Vinod
E-mail: Vinod1@yahoo.com
Emp_Id: E-002
Name: Amit
E-mail: Amit2@yahoo.com
Emp_Id: E-003
Name: Deepak
E-mail: Deepak3@yahoo.com

XML Count Elements


Here providing you an example that counts the number of tags <Emp_Id> that are used in your
XML document using the SAX parser. 

Description of program:

Developing a java program, you need a XML well-formed document. When you run this
program takes a xml file and checks it. If the given file exists, again it takes a tag name. Here we
apply a parameterized constructor (SAXElementCount) that contains xml file. We define a
default handler that implements for all SAX events and overrides two methods like:
startElement() and endDocument(). The startElement method is called by parser each time.
When this method overrides the code checks the given tag and counter is increased (startTag++).
At last the parser reaches the end of document, the endDocument method is called and prints
total number of elements. Any error occurred, exception has been thrown. If file doesn't exist it
will display a message "File not found!". 

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>
</Employee-Detail>

Here is the Java File: SAXElementCount.java

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;

public class SAXElementCount{    
  int startTag = 0;
  public static String ele;
  public static void main(String args[])throws IOException {
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter XML file name:");
    String xmlFile = bf.readLine();
    File file = new File(xmlFile);
    if (file.exists()){
      System.out.print("Enter XML tag name:");
      ele = bf.readLine();
      SAXElementCount tagCount = new SAXElementCount(xmlFile);
    }
    else{
      System.out.println("File not found!");
    }
  }
  public SAXElementCount(String str){
    try{
      SAXParserFactory parserFact = SAXParserFactory.newInstance();
      SAXParser parser = parserFact.newSAXParser();
      DefaultHandler dHandler = new DefaultHandler(){
        public void startElement(String uri, String name, String element, 
                                      Attributes atri)throws SAXException{
          if (element.equals(ele)){
            startTag++;
          }
        }
        public void endDocument(){
          System.out.println("Total elements: " + startTag);
        }
      };
      parser.parse(str,dHandler);
    }
    catch (Exception e){
      e.printStackTrace();
    }
  }
}

Download this example.

Output of program:

C:\vinod\xml>javac
SAXElementCount.java

C:\vinod\xml>java
SAXElementCount
Enter XML file
name:Employee-
Detail.xml
Enter XML tag
name:Emp_Id
Total elements: 3

XML Error Checking and Locating


In this section, you will learn how to check and locate an error in the XML document and error
position. 

Description of program:

The following program helps you in checking and locating an error in XML document.

Implementing this program you need a XML document. When you run the following program
then it asks a xml file name and checks it. If the given file exists, the SAX Parser parses the
XML document and detects the error in it at the specified line and column by using the
getLineNumber() and getColumnNumber() methods. The getLineNumber method detects
line of error and the getColumnNumber method also detects column of error and prints the line
and column. If no any error in XML  document, it will show a message "Employee-Detail.xml is
well-formed". Whenever the given file doesn't exist, it displays "File not found!".

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>


<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod
</Emp_Name>
<Emp_E-mail>
Vinod1@yahoo.com </Emp_E-
mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit
</Emp_Name>
<Emp_E-mail> Amit2@yahoo.com
</Emp_E-mail>
</Employee>

<Employe>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak
</Emp_Name>
<Emp_E-mail>
Deepak3@yahoo.com </Emp_E-
mail>
</Employee>

</Employee-Detail>

Here is the Java File: LocateError.java

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import java.io.*;

public class LocateError{

  public static void main(String[] args) throws IOException{
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter XML file name:");
    String xmlFile = bf.readLine();
    LocateError par = new LocateError(xmlFile);
  }
  
  public LocateError(String str){
    try{
      File file = new File(str);
      if (file.exists()){
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.parse(str);
        System.out.println(str + " is well-formed!");
      }
      else{
        System.out.println("File not found: " + str);
      }
    }
    catch (SAXParseException sax){
      System.out.println(str + " isn't well-formed");
      int line = sax.getLineNumber();
      int col = sax.getColumnNumber();
      System.out.println("Error is at line number "+ line + " 
                                              and Column position "+ col);
    }
    catch (SAXException sax){}
    catch (IOException io){
      System.out.println(io.getMessage());
    }
  }
}

Download this example.

Output of program:

C:\vinod\xml>javac LocateError.java

C:\vinod\xml>java LocateError
Enter XML file name:Employee-Detail.xml
[Fatal Error] Employee-Detail.xml:19:11: The end-
tag for element type "Employe"
must end with a '>' delimiter.
Employee-Detail.xml isn't well-formed
Error is at line number 19 and Column position 11

Getting Attributes And its Value


In this section, you will learn to retrieve the attributes and their value from a XML document
using the SAX APIs. 

Description of program:

This program helps you in retrieving attributes and their values.  The parse() method is  invoked
by the SAXParser object. Override startElement() method in  SAXHandler class to
provide functionality to get the attribute and its value from a xml file. 

Here is the XML File: sample.xml

<Employee-detail >
    <Employee name="Amit" >
        <address>My
address</address>
     </Employee>
     <issued-items> 
        <item code="111"
type="CD" label=" music" />
        <item code="222"
type="DVD" label=" video"/>
     </issued-items>
</Employee-detail>
Here is the Java File: ReadAttributes.java

import java.io.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.util.* ;
import org.apache.xerces.impl.*;
import org.apache.xerces.parsers.*;
import org.apache.xerces.jaxp.*;

public class ReadAttributes {
  public static void main(String[] args) {
    try {
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter a xml file name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if (file.exists()){
        //SAX-implementation:
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // Create SAX-parser
        SAXParser parser = factory.newSAXParser();
        System.out.println("Name:\t" + "Value:");
        //Define a handler
        SaxHandler handler = new SaxHandler();
        // Parse the xml document
        parser.parse(xmlFile, handler);
      }
      else{
        System.out.println("File not found!");
      }
    } 
    catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  private static class SaxHandler extends DefaultHandler {
    public void startElement(String uri, String localName, String qName, 
                    Attributes attrs) throws SAXParseException,SAXException {
      int length = attrs.getLength();
      //Each attribute
      for (int i=0; i<length; i++) {
        // Get names and values to each attribute
        String name = attrs.getQName(i);
        System.out.print(name);
                String value = attrs.getValue(i);
        System.out.println("\t"+value);
      }
    }
  }
}
Download this example.

Output of this program:

C:\vinod\xml\sax1>javac
ReadAttributes.java

C:\vinod\xml\sax1>java
ReadAttributes
Enter a xml file name:
sample.xml
Name:    Value:
name      Amit
code      111
type       CD
label       music
code      222
type       DVD
label      video

Locating the Notified Events


In this section, you will learn to locate (line and column number) the generated events  while
parsing a XML file using SAX APIs. 

Description of program:

This program takes a XML file at the console. Before parsing, the setContentHandler() method
invokes the XMLReader object and it takes DefaultHandler object. The setContentHandler
method allows an application to register a content event handler. The parser starts parsing a
XML document, as soon as  it encounters the root tag at at Line no: 1 Column no: 1, the
startDocument() method is called and the program displays "startDocument() method called at
Line no: 1 Column no: 1" at the console. When parser encounters the first elements, it calls  the
startElement() method and it displays "startElement() method called at Line no: 1 Column no:
19. Similarly, the parser calls characters(), endElement() and endDocument() methods. The
parser displays appropriate messages according to the events generated while parsing a xml
document. 

Here is the XML File: sample.xml

<Employee-detail >
    <Employee name="Amit" >
        <address>My
address</address>
     </Employee>
     <issued-items> 
        <item code="111"
type="CD" label=" music" />
        <item code="222"
type="DVD" label=" video"/>
     </issued-items>
</Employee-detail>

Here is Java File: WorkingSAXParserLocato.java

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.Locator;

public class WorkingSAXParserLocator extends DefaultHandler {
  private Locator locator;
  public static void main(String[] args) {
    try {
      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
      System.out.print("Enter xml file name: ");
      String xmlFile = bf.readLine();
      File file = new File(xmlFile);
      if (file.exists()){
        XMLReader parser = XMLReaderFactory.createXMLReader();
        DefaultHandler handler = new WorkingSAXParserLocator();   
        parser.setContentHandler(handler);
        //parse xml file
        parser.parse(xmlFile);
      }
      else{
        System.out.println("File not found!");
      }
    }
    catch (Exception e) {
      System.err.println(e);
    }
  }
  public void setDocumentLocator(Locator locator) {
    this.locator = locator;
  }
  //All methods positions
  private void printLocation(String location) { 
    int line = locator.getLineNumber();
    int column = locator.getColumnNumber();
    System.out.println(location + "  Line no: " + line + 
                                                   "\tColumn no: " + column);
  }
  //Document start
  public void startDocument() { 
    printLocation("startDocument() method called at");
  }
  //Document end
  public void endDocument() { 
    printLocation("endDocument() method called at");
  }
  //Element start
  public void startElement(String namespaceURI, String localName, 
    String qualifiedName, Attributes atts) {
    printLocation("startElement() method called at ");
  }
  //Element end
  public void endElement(String namespaceURI, String localName, 
    String qualifiedName) {
    printLocation("endElement() method called at \t");
  }
  //characters
  public void characters(char[] text, int start, int length) {
    printLocation("characters() method called at \t"); 
  }
}

Download this example.

Output of this program:

C:\vinod\xml\sax1>javac
WorkingSAXParserLocator.java

C:\vinod\xml\sax1>java
WorkingSAXParserLocator
Enter xml file name: sample.xml
startDocument() method called at  Line
no: 1    Column no: 1
startElement() method called at     Line
no: 1    Column no: 19
characters() method called at        Line
no: 2    Column no: 2
startElement() method called at     Line
no: 2    Column no: 25
characters() method called at        Line
no: 3    Column no: 3
startElement() method called at     Line
no: 3    Column no: 12
characters() method called at        Line
no: 3    Column no: 22
endElement() method called at      Line
no: 3    Column no: 32
characters() method called at        Line
no: 4    Column no: 2
endElement() method called at      Line
no: 4    Column no: 13
characters() method called at        Line
no: 5    Column no: 2
startElement() method called at     Line
no: 5    Column no: 16
characters() method called at        Line
no: 5    Column no: 17
characters() method called at        Line
no: 6    Column no: 3
startElement() method called at     Line
no: 6    Column no: 47
endElement() method called at      Line
no: 6    Column no: 47
characters() method called at        Line
no: 7    Column no: 3
startElement() method called at     Line
no: 7    Column no: 47
endElement() method called at      Line
no: 7    Column no: 47
characters() method called at        Line
no: 8    Column no: 2
endElement() method called at      Line
no: 8    Column no: 17
characters() method called at        Line
no: 9    Column no: 1
endElement() method called at      Line
no: 9    Column no: 19
endDocument() method called at   Line
no: 9    Column no: 19

You might also like