Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java DOM Tutorial

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 51

Java DOM Tutorial

Posted on: February 26, 2008 at 12:00 AM

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.

Java DOM Tutorial


This tutorial is complete guide to DOM processing.
What is DOM? Document Object Model: DOM is a platform- and language-neutral interface, that provides a standard model of how the objects in an XML object are put together, and a standard interface for accessing and manipulating these objects and their inter-relationships. The DOM is an interface that exposes an XML document as a tree structure comprised of nodes. The DOM allows you to programmatically navigate the tree and add, change and delete any of its elements. The DOM programming interface standards are defined by the World

Wide Web

Consortium (W3C). The W3C site provides a comprehensive reference of the XML DOM. 1. Creating Blank DOM Document
This section shows you how to create the blank DOM document.

2. Adding Child Elements to the DOM tree


This lesson shows you how to create root and child elements in the DOM tree.

3. 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.

4. To Count XML Element


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

5. 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.

6. 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.

7. 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.

8. 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.

9. Regenerating XML file


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

10. XML Error checker and locater (DOM)


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

11. 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.

12. Adding DOCTYPE to a XML File


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

13. 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 XMLfragments. 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.

14. 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.

15. 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.

16. 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.

17. 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.).

18. 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.

19. Accessing XML file from Java


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.

Creating Blank DOM Document


Posted on: February 26, 2008 at 12:00 AM

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.

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 section.

Creating DOM Child Elements


Posted on: April 14, 2005 at 12:00 AM

This lesson shows you how to create root and child elements in the DOM tree.

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 import import import javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; 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


Posted on: June 2, 2007 at 12:00 AM

After reading this section, you will be able to retrieve a root element from the XML document.

Getting The XML Root Element


After reading this section, you will be able to retrieve a root element from the XMLdocument. 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 thegetNodeName() 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: EmployeeDetail

To Count XML Element


Posted on: June 4, 2007 at 12:00 AM

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

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 thegetElementByTagName() 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_Email>

</Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email> </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() + " elements."); } 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


Posted on: June 2, 2007 at 12:00 AM

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.

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.DOMParserpackage.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_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email> </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
Posted on: June 4, 2007 at 12:00 AM

In this section, you will learn to check the well-formed-ness of a XML using the DOM interface.

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 DOMparser parsers (parse()) the XML document using the DocumentBuilder andDocumentBuilderFactory. Whenever the XML document is wellformed, 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_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email>

</Employee> </Employee-Detail>
Here is the Java File: DOMParserCheck.java import import import import java.io.*; javax.xml.parsers.*; org.w3c.dom.*; 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


Posted on: June 2, 2007 at 12:00 AM

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.

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_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email> </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 + " Document."); } else{ System.out.println("Element occurrs " + list.getLength() + " times in 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: EmployeeDetail.xml Enter element that have to count: Emp_name Element doesn't exist in the Employee-Detail.xml Document. C:\vinod\xml>java SearchElement Enter file name: EmployeeDetail.xml Enter element that have to count: Emp_Name Element occurrs 3 times in the Employee-Detail.xml

Create - XML File (Document)


Posted on: June 5, 2007 at 12:00 AM

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

Create - XML File (Document)

In this section, you will learn to create aXML 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 Java File: CreatXMLFile.java import import import import import import java.io.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.*; javax.xml.transform.stream.*; 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: JuniorProgrammer <?xml version="1.0" encoding="UTF-8" standalone="no"?><RonseIndia> <Emp-Name>Vino d</Emp-Name><Emp-Code>E001</Emp-Code> <Emp-Desi>JuniorProgrammer</Emp-Desi></Ro nseIndia>

Regenerating XML file


Posted on: June 5, 2007 at 12:00 AM

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

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 Documentobject. 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 aDOM 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_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </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 import import import import import import java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.*; 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: EmployeeDetail.xml <?xml version="1.0" encoding="UTF-8"?><EmployeeDetail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_Email> </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_Email> </Employee> </Employee-Detail>

XML Error checker and locater (DOM)


Posted on: June 8, 2007 at 12:00 AM

In this section, you will learn to check and locate (line and column number) an error in your XML document using the DOM APIs.

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 andDocumentBuilder 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_Email> </Employee </Employee-Detail>
Here is the Java File: DOMLocateError.java import import import import java.io.*; javax.xml.parsers.*; org.w3c.dom.*; 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


Posted on: June 8, 2007 at 12:00 AM

In this section, you will learn to retrieve all elements of the XML file using the DOM APIs.

Getting all XML Elements


In this section, you will learn to retrieve all elements of the XML file using the DOMAPIs. 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. DocumentBuilderobject 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_Email> </Employee>

<Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_Email> </Employee> </Employee-Detail>
Here is Java File: DOMElements.java import import import import java.io.*; javax.xml.parsers.*; org.w3c.dom.*; 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


Posted on: June 8, 2007 at 12:00 AM

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

Adding DOCTYPE to a XML File


In this section, you will learn to add aDOCTYPE 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 theparse() 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_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name>

<Emp_E-mail> Deepak3@yahoo.com </Emp_Email> </Employee> </Employee-Detail>


Here is the Java File: AddDocType.java import import import import import import import java.io.*; javax.xml.parsers.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; 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"); 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


Posted on: June 12, 2007 at 12:00 AM

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.

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 thegetNodeName() 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_Email> </Employee> </Employee-Detail>
Here is the Java File: DisplayElementNodes.java import import import import import import import java.io.*; javax.xml.parsers.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; 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"?><EmployeeDetail> <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


Posted on: June 12, 2007 at 12:00 AM

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.

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_Email> </Employee> </Employee-Detail>
Here is the Java File: DOMCloneElements.java import import import import import import import java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; 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


Posted on: June 12, 2007 at 12:00 AM

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.

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....</Subject> <Body>Be ready for a cruise...</Body> </E-mail>
Here is the Java File: RemoveElement.java

import import import import import import import

java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; 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="UTF8" 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)


Posted on: June 14, 2007 at 12:00 AM

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.

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 needDocumentBuilderFactory and DocumentBuilder. Then we create a Transformer. ThesetOutputProperty() is an abstract method of javax.xml.transform package which invokes theTransformer 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_Email>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_Email> </Employee> </Employee-Detail>
Here is the Java File: GetData.java import import import import import import import java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; 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


Posted on: June 14, 2007 at 12:00 AM

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.).

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 andDocumentBuilder 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_Email>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_Email> </Employee> </Employee-Detail>
Here is the Java File: StoreData.java import import import import import import import java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; 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); 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


Posted on: June 20, 2007 at 12:00 AM

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.

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_Email> </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 import import import import import import import import java.io.*; org.w3c.dom.*; org.xml.sax.*; javax.xml.parsers.*; javax.xml.validation.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; javax.xml.transform.stream.StreamSource; 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> </Employee>

Accessing XML file from Java


Posted on: May 24, 2009 at 12:00 AM

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.

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</lastname> </student-name> <student-address> <address>Rohini</address> <city>Delhi</city> </student-address> </student>
Here is the code of AccessingXmlFile.java import import import import java.io.File; javax.xml.parsers.DocumentBuilder; javax.xml.parsers.DocumentBuilderFactory; org.w3c.dom.*;

public class AccessingXmlFile { public static void main(String argv[]) { try { File file = new File("C:\\MyFile.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(file); document.getDocumentElement().normalize(); System.out.println("Root element "+ document.getDocumentElement().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.getElementsByTagName("firstname"); Element firstNameElement = (Element) firstNameElemntList.item(0); NodeList firstName = firstNameElement.getChildNodes(); System.out.println("First Name:"+ ((Node)firstName.item(0).getNodeValue()); NodeList lastNameElementList = element.getElementsByTagName("lastname"); Element lastNameElement = (Element) lastNameElementList.item(0); NodeList lastName = lastNameElement.getChildNodes(); System.out.println("Last Name :"+ ((Node)lastName.item(0).getNodeValue()); NodeList addressList = element.getElementsByTagName("address"); 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)).getNodeValue()); } } } 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:

You might also like