0% found this document useful (0 votes)
42 views51 pages

Java DOM Processing Tutorial

This tutorial provides instructions on how to create a DOM document in Java and add elements to the DOM tree to build an XML document. It shows how to create a blank DOM document, add a root element, create a comment element, and add a child element with an attribute. The full XML document output is displayed consisting of a root element containing a comment and a child element with an attribute.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views51 pages

Java DOM Processing Tutorial

This tutorial provides instructions on how to create a DOM document in Java and add elements to the DOM tree to build an XML document. It shows how to create a blank DOM document, add a root element, create a comment element, and add a child element with an attribute. The full XML document output is displayed consisting of a root element containing a comment and a child element with an attribute.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

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 [Link] 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 [Link] 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 [Link] 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 = [Link](); DocumentBuilder parser = [Link](); Document doc = [Link](myInputSource); //The parse function is used to parse existing xml document.

DocumentBuilderFactory uses the system property [Link] to find the class to load. So you can change the parser by calling: [Link]("[Link]", "[Link]"); 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 = [Link](); Here is the full code of [Link] import [Link].*; import [Link]; import [Link]; public class CreateBlankDocument { public static void main(String[] args) { [Link]("Creating Balnk Document..."); try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = [Link](); //Get the DocumentBuilder DocumentBuilder parser = [Link]();

//Create blank DOM Document Document doc = [Link](); }catch(Exception e){ [Link]([Link]()); } [Link]("Done..."); [Link]("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 = [Link](); 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 = [Link]("root"); //all it to the xml tree [Link](root); Adding Comment Element to DOM Tree The [Link] function is used to create Comment object. //create a comment Comment comment = [Link]("This is comment"); //add in the root element [Link](comment); Adding Child Element to DOM Tree The [Link] function is used to create Child element. //create child element Element childElement = [Link]("Child"); //Add the atribute to the child [Link]("attribute1","The value of Attribute 1"); [Link](childElement); Printing the DOM Tree on console An finally we will print the DOM tree on the console with the following code: TransformerFactory tranFactory = [Link](); Transformer aTransformer = [Link](); Source src = new DOMSource(doc);

Result dest = new StreamResult([Link]); [Link](src, dest); Here is the full code of [Link] import [Link].*; import import import import [Link].*; [Link].*; [Link]; [Link];

class CreateDomXml { public static void main(String[] args) { try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = [Link](); //Get the DocumentBuilder DocumentBuilder docBuilder = [Link](); //Create blank DOM Document Document doc = [Link](); //create the root element Element root = [Link]("root"); //all it to the xml tree [Link](root); //create a comment Comment comment = [Link]("This is comment"); //add in the root element [Link](comment); //create child element Element childElement = [Link]("Child"); //Add the atribute to the child [Link]("attribute1","The value of Attribute 1"); [Link](childElement); TransformerFactory tranFactory = [Link](); Transformer aTransformer = [Link](); Source src = new DOMSource(doc); Result dest = new StreamResult([Link]); [Link](src, dest); }catch(Exception e){ [Link]([Link]()); }

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: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_E-mail> </Employee>

<Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@[Link] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@[Link] </Emp_E-mail> </Employee> </Employee-Detail>
Here is the Java File: [Link] import [Link].*; import [Link].*; import [Link].*; public class GetRootNode{ public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter xml file name: "); String str = [Link](); File file = new File(str); if ([Link]()){ DocumentBuilderFactory fact = [Link](); DocumentBuilder builder = [Link](); Document doc = [Link](str); Node node = [Link](); String root = [Link](); [Link]("Root Node: " + root); } else{ [Link]("File not found!"); } } catch(Exception e){} } }

Download this example.


Output of the program:

C:\vinod\xml>javac

[Link] C:\vinod\xml>java GetRootNode Enter xml file name: [Link] 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: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email>

</Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@[Link] </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: [Link] import [Link].*; import [Link].*; import [Link].*; public class DOMCountElement{ public static void main(String[] args) { try { BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter File name: "); String xmlFile = [Link](); File file = new File(xmlFile); if ([Link]()){ DocumentBuilderFactory factory = [Link](); // Create the builder and parse the file Document doc = [Link]().parse(xmlFile); [Link]("Enter element name: "); String element = [Link](); NodeList nodes = [Link](element); [Link]("xml Document Contains " + [Link]() + " elements."); } else{ [Link]("File not found!"); } }

catch (Exception ex) { [Link](ex); } }

Download this example.


Output of program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java DOMCountElement Enter File name: [Link] 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 [Link] 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 [Link] package. Your classpath must contain [Link] and [Link] 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 [Link] 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: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@[Link] </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: [Link] import [Link].*; import [Link]; import [Link].*; public class CountNodes{ public static void main(String[] args) { try{

BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter file name: "); String str = [Link](); File file = new File(str); if ([Link]()){ DOMParser parser = new DOMParser(); [Link](str); Document doc = [Link](); [Link]("Enter element that have to count: "); String ele = [Link](); NodeList list = [Link](ele); [Link]("Number of nodes: " + [Link]()); } else{ [Link]("File not found!"); } } catch (Exception e){ [Link](); } }

Download this example.


Output of program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java CountNodes Enter file name: [Link] 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 "[Link] is well-formed". Otherwise it displays "[Link] isn't well-formed.". Here is the XML File: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@[Link] </Emp_Email>

</Employee> </Employee-Detail>
Here is the Java File: [Link] import import import import [Link].*; [Link].*; [Link].*; [Link].*;

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

Download this example.


Output of program:

C:\vinod\xml>javac [Link]

C:\vinod\xml>java DOMParserCheck Enter File name: [Link] [Link] 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 [Link] 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 [Link] package. Your classpath must contain [Link] and [Link] 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 [Link]. 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 [Link] Document." Else it counts a given element Here is the XML File: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id>

<Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@[Link] </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: [Link] import [Link].*; import [Link]; import [Link].*; public class SearchElement{ public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter file name: "); String str = [Link](); File file = new File(str); if ([Link]()){ DOMParser parser = new DOMParser(); [Link](str); Document doc = [Link](); [Link]("Enter element that have to count: "); String ele = [Link](); NodeList list = [Link](ele); if([Link]() == 0){ [Link]("Element doesn't exist in the " +

str + " Document."); } else{ [Link]("Element occurrs " + [Link]() + " times in the " + str); } } else{ [Link]("File not found!"); } } catch (Exception e){ [Link](); } } }

Download this example.


Output of program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java SearchElement Enter file name: [Link] Enter element that have to count: Emp_name Element doesn't exist in the [Link] Document. C:\vinod\xml>java SearchElement Enter file name: [Link] Enter element that have to count: Emp_Name Element occurrs 3 times in the [Link]

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: [Link] import import import import import import [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link].*;

public class CreatXMLFile { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter number to add elements in your XML file: "); String str = [Link](); int no = [Link](str); [Link]("Enter root: "); String root = [Link](); DocumentBuilderFactory documentBuilderFactory = [Link](); DocumentBuilder documentBuilder = [Link](); Document document = [Link](); Element rootElement = [Link](root); [Link](rootElement); for (int i = 1; i <= no; i++){ [Link]("Enter the element: "); String element = [Link](); [Link]("Enter the data: "); String data = [Link](); Element em = [Link](element); [Link]([Link](data)); [Link](em); } TransformerFactory transformerFactory = [Link]();

Transformer transformer = [Link](); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult([Link]); [Link](source, result); } }

Download this example.


Output of this program:

C:\vinod\xml>javac [Link] 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 "[Link]" shows the result on the console. Here is the XML File: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@[Link] </Emp_E-

mail> </Employee> </Employee-Detail>


Here is the Java File: [Link] import import import import import import import [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link].*;

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

Download this example.


Output of this program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java GetElementsDOM Enter XML File Name: [Link] <?xml version="1.0" encoding="UTF-8"?><EmployeeDetail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@[Link] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@[Link] </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 "[Link] is well-formed!". Otherwise, it displays an error and exact error location (line and column number). Here is the XML File: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee </Employee-Detail>
Here is the Java File: [Link] import import import import [Link].*; [Link].*; [Link].*; [Link].*;

public class DOMLocateError{ static public void main(String[] arg){

try { BufferedReader bf = new BufferedReader(new InputStreamReader([Link])); [Link]("Enter File name: "); String xmlFile = [Link](); File file = new File(xmlFile); if([Link]()){ // Create a new factory DocumentBuilderFactory factory = [Link](); // Use the factory to create builder document. DocumentBuilder builder = [Link](); Document doc = [Link](xmlFile);

[Link](xmlFile + " is well-formed!");


} else{ [Link]("File not found!"); } } catch (SAXParseException e) { [Link]("type" + ": " + [Link]()+"\n"); [Link]("Line " + [Link]() + " Column " + [Link]()); } catch (SAXException e) { [Link](e); [Link](1); } catch (ParserConfigurationException e) { [Link](e); [Link](1); } catch (IOException e) { [Link](e); [Link](1); } }

Download this example.


Output of this program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java DOMLocateError Enter File name: [Link] [Fatal Error] [Link]: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 ([Link]) 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: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee>

<Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@[Link] </Emp_Email> </Employee> </Employee-Detail>
Here is Java File: [Link] import import import import [Link].*; [Link].*; [Link].*; [Link].*;

public class DOMElements{ static public void main(String[] arg){ try { BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter XML File name: "); String xmlFile = [Link](); File file = new File(xmlFile); if([Link]()){ // Create a factory DocumentBuilderFactory factory = [Link](); // Use the factory to create a builder DocumentBuilder builder = [Link](); Document doc = [Link](xmlFile); // Get a list of all elements in the document NodeList list = [Link]("*"); [Link]("XML Elements: "); for (int i=0; i<[Link](); i++) { // Get element Element element = (Element)[Link](i); [Link]([Link]()); }

} else{ [Link]("File not found!"); } } catch (Exception e) { [Link](1); } } }

Download this example.


Output of this program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java DOMElements Enter XML File name: [Link] 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: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@[Link] </Emp_Email> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name>

<Emp_E-mail> Deepak3@[Link] </Emp_Email> </Employee> </Employee-Detail>


Here is the Java File: [Link] import import import import import import import [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link]; [Link];

public class AddDocType{ static public void main(String[] args){ try{ BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter XML file name: "); String xmlFile = [Link](); [Link](); File file = new File(xmlFile); if ([Link]()){ DocumentBuilderFactory factory = [Link](); DocumentBuilder builder = [Link](); Document doc = [Link](xmlFile); // Create transformer Transformer tFormer = [Link]().newTransformer(); // Set system id [Link]( OutputKeys.DOCTYPE_SYSTEM, "systmId"); Source source = new DOMSource(doc); Result result = new StreamResult([Link]); [Link](source, result); [Link](); } else{ [Link]("File not found!"); } } catch (Exception e){ [Link](); } }

Download this example.


Output of this program: XML docType SystemId and publicId

C:\vinod\xml>java AddDocType Enter XML file name: [Link] <?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@[Link] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Sushil </Emp_Name> <Emp_E-mail>Sushil@[Link] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit@[Link] </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 "[Link]" to display the data on the console. Here is the XML File: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: [Link] import import import import import import import [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link]; [Link];

public class DisplayElementNodes { static public void main(String[] arg){ try{ BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter a XML file name: "); String xmlFile = [Link]();

File file = new File(xmlFile); if ([Link]()){ DocumentBuilderFactory factory = [Link](); DocumentBuilder builder = [Link](); Document doc = [Link](xmlFile); TransformerFactory tranFactory = [Link](); Transformer aTransformer = [Link](); // Get nodes list of all elements NodeList list = [Link]("*"); for (int i=0; i<[Link](); i++){ // Get element Element element = (Element)[Link](i); Source src = new DOMSource(element); [Link]("Node no: " + i + " is " + [Link]()); [Link]( "Its corresponding xml representation:"); Result dest = new StreamResult([Link]); [Link](src, dest); [Link]("\n"); } } else{ [Link](xmlFile + " (file name) doesn't found!"); } } catch (Exception e){ [Link](); } } }

Download this example.


Output of this program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java DisplayElementNodes Enter a XML file name: [Link] 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@[Link] </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@[Link] </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@[Link] </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 [Link](true) method creates a clone and [Link]().insertBefore(copyElement, [Link]())inserts the clone element at the specified position. Here is the XML File: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: [Link] import import import import import import import [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link]; [Link];

public class DOMCloneElements { static public void main(String[] arg){ try { BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter XML file name: "); String xmlFile = [Link](); File file = new File(xmlFile); if ([Link]()){ DocumentBuilderFactory factory = [Link](); DocumentBuilder builder = [Link](); Document doc = [Link](xmlFile); TransformerFactory tFactory = [Link](); Transformer tformer = [Link]();

Source source = new DOMSource(doc); Result result = new StreamResult([Link]); [Link](xmlFile + " file: "); [Link](source, result); [Link](); [Link]("Enter the element to clone: "); String clone = [Link](); [Link]("Enter data to add: "); String addElement = [Link](); //////////////////////////////// NodeList list = [Link](clone); Element element1 = (Element)[Link](0); Element copyElement = (Element) [Link](true); [Link]().insertBefore(copyElement, [Link]()); [Link]([Link](addElement)); [Link](source, result); } else{ [Link]("File not found!"); } } catch (Exception e){ [Link](); } }

Download this example.


Output of this program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java DOMCloneElements Enter XML file name: [Link] [Link] 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@[Link] </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@[Link] </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:[Link]

<?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: [Link]

import import import import import import import

[Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link]; [Link];

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

Download this example.


Output of this program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java RemoveElement Enter a XML file name: [Link]

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 [Link] 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: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Sushil </Emp_Name> <Emp_Email>Sushil@[Link] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit@[Link] </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: [Link] import import import import import import import [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link]; [Link];

public class GetData{ static public void main(String[] arg) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter XML file name: ");

String xmlFile = [Link](); File file = new File(xmlFile); if ([Link]()){ DocumentBuilderFactory factory = [Link](); DocumentBuilder builder = [Link](); Document doc = [Link](xmlFile); // Create transformer Transformer tFormer = [Link]().newTransformer(); // Output text type [Link]([Link], "text"); // Write the document to a file Source source = new DOMSource(doc); Result result = new StreamResult([Link]); [Link](source, result); } else{ [Link]("File not found!"); } } catch (Exception e){ [Link](e); [Link](0); } } }

Download this example.


Output of this program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java GetData Enter XML file name: [Link] E-001 Vinod Vinod1@[Link] E-002 Sushil Sushil@[Link] E-003 Amit

Amit@[Link]

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: [Link], [Link], [Link],[Link] etc. from the XML document. Here is the XML File: [Link]

<?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Sushil </Emp_Name> <Emp_Email>Sushil@[Link] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit@[Link] </Emp_Email> </Employee> </Employee-Detail>
Here is the Java File: [Link] import import import import import import import [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link]; [Link];

public class StoreData{ static public void main(String[] arg) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader([Link])); [Link]("Enter XML file name: ");

String xmlFile = [Link](); File file = new File(xmlFile); if ([Link]()){ DocumentBuilderFactory factory = [Link](); DocumentBuilder builder = [Link](); Document doc = [Link](xmlFile); // Create transformer Transformer tFormer = [Link]().newTransformer(); // Output Types (text/xml/html) [Link]([Link], "text"); // Write the document to a file Source source = new DOMSource(doc); Result result = new StreamResult(new File("[Link]")); [Link](source, result); [Link]("File creation successfully!"); } else{ [Link]("File not found!"); } } catch (Exception e){ [Link](e); [Link](0); } } }

Download this example.


Output of program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java StoreData Enter XML file name: [Link] 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, "[Link]") in the transformer object. Here is the xml file: [Link]

<?xml version = "1.0" ?> <!DOCTYPE Employee SYSTEM "[Link]"> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </Emp_Email> </Employee>
Here is the DTD File: [Link]

<!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: [Link] import import import import import import import import import [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link].*; [Link]; [Link]; [Link];

public class DOMValidateDTD { public static void main(String args[]) { try{ DocumentBuilderFactory factory = [Link](); [Link](true); DocumentBuilder builder = [Link](); [Link](new [Link]() { //Ignore the fatal errors public void fatalError(SAXParseException exception) throws SAXException { } //Validation errors public void error(SAXParseException e) throws SAXParseException { [Link]("Error at " +[Link]() + " line."); [Link]([Link]()); [Link](0); } //Show warnings public void warning(SAXParseException err) throws SAXParseException{ [Link]([Link]()); [Link](0); } }); Document xmlDocument = [Link]( new FileInputStream("[Link]")); DOMSource source = new DOMSource(xmlDocument); StreamResult result = new StreamResult([Link]); TransformerFactory tf = [Link](); Transformer transformer = [Link](); [Link]( OutputKeys.DOCTYPE_SYSTEM, "[Link]"); [Link](source, result); }

catch (Exception e) { [Link]([Link]()); } }

Download this example.


Output of this program:

C:\vinod\xml>javac [Link] C:\vinod\xml>java DOMValidateDTD <?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE Employee SYSTEM "[Link]"> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@[Link] </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) [Link] 2) [Link] Source Code for accessing XML file through Java

File [Link]

<?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 [Link] import import import import [Link]; [Link]; [Link]; [Link].*;

public class AccessingXmlFile { public static void main(String argv[]) { try { File file = new File("C:\\[Link]"); DocumentBuilderFactory dbf = [Link](); DocumentBuilder db = [Link](); Document document = [Link](file); [Link]().normalize(); [Link]("Root element "+ [Link]().getNodeName()); NodeList node = [Link]("student"); [Link]("Information of the students"); for (int i = 0; i < [Link](); i++) { Node firstNode = [Link](i); if ([Link]() == Node.ELEMENT_NODE) { Element element = (Element) firstNode;

NodeList firstNameElemntList = [Link]("firstname"); Element firstNameElement = (Element) [Link](0); NodeList firstName = [Link](); [Link]("First Name:"+ ((Node)[Link](0).getNodeValue()); NodeList lastNameElementList = [Link]("lastname"); Element lastNameElement = (Element) [Link](0); NodeList lastName = [Link](); [Link]("Last Name :"+ ((Node)[Link](0).getNodeValue()); NodeList addressList = [Link]("address"); Element addressElement = (Element) [Link](0); NodeList address = [Link](); [Link]("Address : " + ((Node) [Link](0)).getNodeValue()); NodeList cityList = [Link]("city"); Element cityElement = (Element) [Link](0); NodeList city = [Link](); [Link]("City : " + ((Node) [Link](0)).getNodeValue()); } } } catch (Exception e) { [Link](); }

} }

In the above example, the method [Link]() 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