You are on page 1of 33

RAJALAKSHMI INSTITUTE OF TECHNOLOGY,CHENNAI

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

2010-2011

LAB MANUAL

CS2358 INTERNET PROGRAMMING LABORATORY

III YEAR

VI SEMESTER
SYLLABUS
CS2358 INTERNET PROGRAMMING LAB LTPC
0032
LIST OF EXPERIMENTS
1.Create a web page with the following using HTML
i) To embed an image map in a web page
ii) To fix the hot spots
iii) Show all the related information when the hot spots are clicked.
2. Create a web page with all types of Cascading style sheets.
3. Client Side Scripts for Validating Web Form Controls using DHTML
4. Write programs in Java to create applets incorporating the following features:
 Create a color palette with matrix of buttons
 Set background and foreground of the control text area by selecting a color from
color palette.
 In order to select Foreground or background use check box control as radio
buttons
 To set background images
5. Write programs in Java using Servlets:
 To invoke servlets from HTML forms
 To invoke servlets from Applets
6. 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.
7. Programs using XML – Schema – XSLT/XSL
8. Program using DOM / SAX
9. Programs using AJAX
10. Consider a case where we have two web Services- an airline service and a travel
agent and the travel agent is searching for an airline. Implement this scenario using
Web Services and Data base.

2
LIST OF EXPERIMENTS

PAGE.
S.NO NAME OF THE EXPERIMENT
NO.

1. 4
IMAGE MAP

2. 7
CASCADING STYLE SHEETS

3. 10
CLIENT SIDE SCRIPTING

4. 14
APPLET PROGRAMMING

5. 18
SERVLET PROGRAMMING

6. 21
ONLINE EXAMINATION USING JSP

7. 26
XML SCHEMA

8. 28
AJAX

9. 29
DOM

10 31
SAX

3
Ex No: 1 IMAGE MAP

Aim:

Create a web page with the following using HTML

 To embed an image map in a web page


 To fix the hot spots
 Show all the related information when the hot spots are clicked.

Algorithm:

 To Embed an image using the Image Tag <img>


<area shape=”cords=” “href=” “alt=””/>

 To create a map with different attributes


<map name=”planet map”>

 To fix the hotspots with the different styles

1) Circle:

<area shape=”circle” cords=”0, 0, 82,126” href=”sun.htm” alt=”sun”>

2) Rectangle:

<area shape=”rect” cords=”0, 0, 82,126” href=”sun.htm” alt=”sun”>

 Create a web pages related to the hotspot


 Open a browser and display the web pages

Program code:

<html>
<title> Image Map </title>
<center><h4>SUN AND PLANETS</h4>
<body>
<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap" />
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.html" alt="Sun" />
<area shape="circle" coords="90,58,3" href="mercury.html" alt="Mercury" />
<area shape="circle" coords="124,58,8" href="venus.html" alt="Venus" />
</map>
</body>
4
</html>

<html>
<title>Sun</title>
<body>
<h5>VENUS</h5>
<p>
Venus is the second planet from the Sun, orbiting it every 224.7 Earth days. The planet is named after Venus,
the Roman goddess of love and beauty. After the Moon, it is the brightest natural object in the night sky,
reaching an apparent magnitude of -4.6, bright enough to cast shadows. Because Venus is an inferior planet
from Earth, it never appears to venture far from the Sun: its elongation reaches a maximum of 47.8°. Venus
reaches its maximum brightness shortly before sunrise or shortly after sunset, for which reason it has been
known as the Morning Star or Evening Star.
</p><a href="exp1.html">home</a>
</body>
</html>

<html>
<title>Sun</title>
<body>
<h5>SUN</h5>
<p>
The Sun is the star at the center of the Solar System.
It has a diameter of about 1,392,000 km, about 109 times that of Earth, and its mass (about 2×1030 kilograms,
330,000 times that of Earth) accounts for about 99.86% of the total mass of the Solar System.
About three quarters of the Sun's mass consists of hydrogen, while the rest is mostly helium. Less than 2%
consists of heavier elements, including oxygen, carbon, neon, iron, and others.
</p><a href="exp1.html">home</a>
</body>
</html>

<html>
<title>Sun</title>
<body>
<h5>MERCURY</h5>
<p>
Mercury is the innermost and smallest planet in the Solar System, orbiting the Sun once every 87.969 Earth
days. The orbit of Mercury has the highest eccentricity of all the Solar System planets, and it has the smallest
axial tilt.It completes three rotations about its axis for every two orbits. The perihelion of Mercury's orbit
precesses around the Sun at an excess of 43 arcseconds per century; a phenomenon that was explained in the
20th century by Albert Einstein's General Theory of Relativity.Mercury is bright when viewed from Earth,
ranging from -2.3 to 5.7 in apparent magnitude, but is not easily seen as its greatest angular separation from the
Sun is only 28.3°. Since Mercury is normally lost in the glare of the Sun, unless there is a solar eclipse it can be
viewed from Earth's Northern Hemisphere only in morning or evening twilight, while its extreme elongations
occur in Declinations south of the celestial equator, such that it can be seen at favorable apparitions from
moderate latitudes in the Southern Hemisphere in a fully dark sky.
</p>
<a href="exp1.html">home</a>
5
</body>
</html>

6
Ex No: 2 CASCADING STYLE SHEETS

Aim:

Create a web page with all types of Cascading style sheets.

Algorithm:

 Start the cascading program

 Give link from main page to other like cascading, Embedded.

 There are three types of cascading style sheets


1)Internal
2)External
3)Inline
 External style sheets which we include should have separate CSS file
 Write the code for separate page finally terminate program.

Program code:
<html>
<head><title>CSS home</title>
<style type="text/css">
body
{background-color:#d0e4fe;}
h2
{color:orange;
text-align:center;}
p
{font-family:"Times New Roman";
font-size:20px;}
</style></head>
<body>
<h2>Types of CSS</h2>
<ul>
<a href="iss.html"><li>Internal style sheets</li></a>
<a href="ess.html"><li>External style sheets</li></a>
<a href="is.html"><li>Inline styles</li></a>
</body>
</html>

<html>
<head>
<title>External style sheets</title>
<link REL="StyleSheet" TYPE="text/css" HREF="csscode.css"/>
</head>
7
<body><center><h2>External Style Sheets</h2></center>
<p>A CSS file contains no (X)HTML, only CSS.</p>
<p> You simply save it with the .css file extension.</p>
<p> You can link to the file externally by placing one of the following links in the head section of every
(X)HTML file you want to style with the CSS file.</p>
</body>
</html>
Csscode.css
p
{font-family:arial;
color:red;
font-size:15px;
}

<html>
</head><title>Inline style sheets</title></head>
<body>
<center><h2 style="font-color:blue;">Inline styles</h2></center>
<p style="font-family:verdana;color:red">
Inline styles are defined right in the (X)HTML file along side the element you want to style.</p>
</html>

<html>
</head><title>Internal style sheets</title>
<style type="text/css">
body
{background-color:red;}
h2
{color:blue;
text-align:center;}
p
{font-family:"calibra";
font-size:15px;}
</style></head>
<body><h2>Internal style sheets</h2>
<p>CSS code within the head tag. </P>
<p>File contains the CSS code needed to style the page.</p>
<p> Meaning that any changes you want to make to one page, will have to be made to all. </body></p>
</html>

8
9
Ex No: 3 CLIENT SIDE SCRIPTING

Aim:

To write a Client Side Script for Validating Web Form Controls using DHTML.

Algorithm:

 This form will include one text field called “Your name “ and submit button

 Validation script will ensure that the user enters their name before the form is sent to the server

 Open this page to see it in action

 Try pressing the send details button without filling anything in the Your name” field

 You might like to open the source code for this form in a separate window

 The page consists of a java script function called Validate Form() that performs the form validation
followed by the form itself

Program code:
<html>
<head>
<title>Student Registration Form</title>
<script language="JavaScript">
function validate()
{
var i;
var name_str=document.my_form.name1;
var phoneID=document.my_form.ph_txt;
var ph_str=document.my_form.ph_txt.value;
var str=document.my_form.Email_txt.value;
if((name_str.value==null)||(name_str.value==""))
{
alert("Enter some name");
return false;
}
if(document.my_form.Age_txt.value=="")
{
alert("invalid age");
return false;
}
if(ph_str.length<1||ph_str.length>11)
{
alert("Invalid length of phone number");
return false;
10
}
for(i=0;i<ph_str.length;i++)
{
var ch=ph_str.charAt(i);
if(((ch<"0")||(ch>"9")))
{
alert("Invalid phone number")
phoneID.focus();
return false;
}
}
var index_at=str.indexOf("@");
var len=str.length;
var index_dot=str.indexOf(".");
var emailID=document.my_form.Email_txt;
if((emailID.value==null)||(emailID.value==""))
{
alert("Please Enter your Email ID");
emailID.focus();
return false;
}
if(str.indexOf("@")==-1)
{
alert("Invalid E-mail ID");
return false;
}
if(str.indexOf(".")==-1||str.indexOf(".")==0||str.indexOf(".")==index_at)
{
alert("invalid mail id");
return false;
}
if(str.indexOf("@",(index_at+1))!=-1)
{
alert("invalid mail ID");
return false;
}
if(str.indexOf(" ")!=-1)
{
alert("Invalid E-mail id");
return false;
}
if((!document.my_form.group1[0].checked) &&( !document.my_form.group1[1].checked))
{
alert("please select sex");
return false;
}
if((!document.my_form.option1[0].checked)||(!document.my_form.option1[1].checked)||
(document.my_form.option1[1].checked))
11
{
alert("please select hoppy");
return false;
}
alert("Registered succesfully");
return true;
}
</script>
</head>
<body bgcolor=aqua>
<center><h3>Application Forum</h3></center>
<form name=my_form OnSubmit=validate()>
<strong>Name:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</strong>
<input type=text name=name1><br/>
<strong>Age:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</strong>
<input type=text name=Age_txt><br/>
<strong>Phone No:&nbsp</strong>
<input type=text name=ph_txt><br/>
<strong>Email:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</strong>
<input type=text name=Email_txt><br/><br/>
<strong>sex:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</strong>
<input type="radio" name="group1" value="male">Male&nbsp&nbsp&nbsp&nbsp
<input type="radio" name="group1" value="female">Female<br/><br/><br/>
<strong>Hobby:</strong> &nbsp&nbsp
<input type="checkbox" name="option1" value="singing">singing<br/>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<input type="checkbox" name="option1" value="dancing">dancing<br/>
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<input type="checkbox" name="option1" value="gaming">gaming<br/>
<br/><br/>
<strong>country:</strong>
<select name="My_Menu">
<option value="India">India</option>
<option value="China">China</option>
<option value="Lanka">Lanka</option>
</select>
<center>
<input type=submit value=submit></br>
</center>
</body>
</form>
</html>

12
13
Ex No:4 APPLET PROGRAMMING

Aim:

Write programs in Java to create applets incorporating the following features:

 Create a color palette with matrix of buttons

 Set background and foreground of the control text area by selecting a color from
color palette.

 In order to select Foreground or background use check box control as radio buttons
 To set background images

Algorithm:

 With the grid layout you specify the number of rows and columns

 Then the components are added from left to right.

 When the row becomes full, the next row is started.

 To increase and decrease the size of the window.

 In this case, you will see the sizes changing for the components instead of the positions, as you saw with
the flow layout.

 The format of the constructor is (last 2 parameters are optional)

 Test modifying the parameters list form.

 GridLayout nature =new GridLayout(3,3,10,10)

 Place the TextArea and insert image to the Applet.

Program Code:
/* <applet code=palette height=400 width=600>
</applet> */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class palette extends Applet implements ActionListener,ItemListener
{
Button[] colors;
14
Checkbox foreground,background;
TextArea workarea;
CheckboxGroup cbg;
Panel buttonpanel,checkpanel,palettepanel;
String colour;
public void init()
{
buttonpanel=new Panel();
buttonpanel.setLayout(new GridLayout(3,3));
colors=new Button[9];
colors[0]=new Button("RED");
colors[1]=new Button("GREEN");
colors[2]=new Button("BLUE");
colors[3]=new Button("CYAN");
colors[4]=new Button("ORANGE");
colors[5]=new Button("WHITE");
colors[6]=new Button("BLACK");
colors[7]=new Button("YELLOW");
colors[8]=new Button("PINK");
for(int i=0;i<9;i++)
{
colors[i].addActionListener(this);
buttonpanel.add(colors[i]);
}
checkpanel=new Panel();
checkpanel.setLayout(new FlowLayout());
cbg=new CheckboxGroup();
foreground=new Checkbox("ForeGround",cbg,true);
background=new Checkbox("BackGround",cbg,false);
foreground.addItemListener(this);
background.addItemListener(this);
checkpanel.add(foreground);
checkpanel.add(background);
workarea=new TextArea(8,40);
workarea.setFont(new Font("Garamond",Font.BOLD,20));
palettepanel=new Panel();
palettepanel.setLayout(new BorderLayout());
palettepanel.add(workarea,BorderLayout.CENTER);
palettepanel.add(checkpanel,BorderLayout.EAST);
palettepanel.add(buttonpanel,BorderLayout.SOUTH);
add(palettepanel);
}
public void itemStateChanged(ItemEvent ie)
{}
public void actionPerformed(ActionEvent ae)
{
colour=ae.getActionCommand();
if(foreground.getState()==true)
15
workarea.setForeground(getColour());
if(background.getState()==true)
workarea.setBackground(getColour());
}
public Color getColour()
{
Color mycolor=null;
if(colour.equals("RED"))
mycolor=Color.red;
if(colour.equals("GREEN"))
mycolor=Color.green;
if(colour.equals("BLUE"))
mycolor=Color.blue;
if(colour.equals("CYAN"))
mycolor=Color.cyan;
if(colour.equals("ORANGE"))
mycolor=Color.orange;
if(colour.equals("WHITE"))
mycolor=Color.white;
if(colour.equals("BLACK"))
mycolor=Color.black;
if(colour.equals("YELLOW"))
mycolor=Color.yellow;
if(colour.equals("PINK"))
mycolor=Color.pink;
return mycolor;
}
}

16
17
Ex No: 5 SERVLET PROGRAMMING

Aim:

Write programs in Java using Servlets:

 To invoke servlets from HTML forms

Algorithm:

 Create a new web project.

 Create the java application logic that represents the Java servlet.

 Create the web page for the web application

 Package the web application to a WAR file.

 Deploy the WAR file to the J2EE application server.

 Test your web application.

Program code:
<html>
<head>
<title>Student information form</title>
</head>
<body>
<center>
<form name="form1" action="http://localhost:8080/">
<h3>Enter student information in following fields</h3>
<table>
<tr>
<td><b>Roll number</b></td>
<td><input type="text" name="RollNumber" size="25" value=""></td>
</tr>
<tr>
<td><b>Student name</b></td>
<td><input type="text" name="Student Name" size="25" value=""></td>
</tr>
<tr>
<td><b>Student address</b></td>
<td><input type="text" name="Address" size="50" value=""></td>
</tr>
<tr>
<td><b>Phone</b></td>
18
<td><input type="text" name="Phone" size="10" value=""></td>
</tr>
<tr>
<td><b>Total marks</b></td>
<td><input type="text" name="Total marks" size="10" value=""></td>
</tr>
</table>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>

import java.io.*;
import java.util.*;
import javax.servlet.*;
public class my_servletDemo extends GenericServlet
{
public void service(ServletRequest req.ServletResponse res) throws ServlerException,IOException
{
PrintWriter out=res.getWriter();
Enumeration en=req.getParameterNames();
while(en.hasMoreElements())
{
String name_received=(String)en.nextElement();
out.print(name_received+"=");
String value_received=req.getPArameter(name_received);
out.println(value_received);
out.println("");
}
out.close();
}
}

19
20
Ex No: 6 ONLINE EXAMINATION USING JSP

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.

Algorithm:

 First install tomcat server into the system.

 Then make a subdirectory in the \tomcat\Webapps.

 Under tr create WEB-INF directory and also place the html files in this directory

 Next under WEB-INF create two subclasses and web.xml

 Next place all the class files under the classes and jar files (servlet-api.jar, classes12.jar etc..) under lib
directories.

 After this start tomcat by giving the following command at the install_dir>tomcat>bin

 Catalina.bat run

 At the I.E(web browser)give the url as http://localhost:8080//tr//htmlfile or servlet url pattern


 Port no 8080 is assigned for the tomcat.

Program code:
<%@pagelanguage="java" import="java.sql.*"%>
<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%
String seatnum,name;
String ans1,ans2,ans3,ans4,ans5;
int a1,a2,a3,a4,a5;
a1=a2=a3=a4=a5=0;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:jspdns","","");
if(request.getParameter("action")!=null)
{

21
seatnum=request.getParameter("seat_no");
name=request.getParameter("Name");
ans1=request.getParameter("group1");
if(ans1.equals("True"))
a1=2;
else
a1=0;
ans2=request.getParameter("group2");
if(ans2.equals("True"))
a2=0;
else
a2=2;
ans3=request.getParameter("group3");
if(ans3.equals("True"))
a3=0;
else
a3=2;
ans4=request.getParameter("group4");
if(ans4.equals("True"))
a4=2;
else
a4=0;
ans5=request.getParameter("group5");
if(ans5.equals("True"))
a5=0;
else
a5=2;
int Total=a1+a2+a3+a4+a5;
stmt=con.createStatement();
String query="INSERT INTO table1 VALUES("'+seatnum+'"+"'+name+'","'+Total+'")";
stmt.close();
stmt=con.createStatement();
query="SELECT * FROM table1 WHERE name="+""'+name+'"";
re=stmt.executeQuery(query);
%>
<html>
<head>
<title>
STudent Mark List
</title>
</head>
<body bgcolor=khaki>
<center>
<h2>Students MArksheet</h2>
<h3>Name of the college:RIT</h3>
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td><b>Seat_no</b></td>
22
<td><b>Name</b></td>
<td><b>Marks</b></td>
</tr>
<%
while(re.next())
{
%>
<tr>
<td><%=rs.getInt(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
</tr>
<%
}
rs.clode();
stmt.close();
con.close();
%>
</table>
</center>
<br/><br/><br/>
<table>
<tr><td>Date:<%=new java.util.Date().toString()%></td></tr>
<tr><td><b>Signature:x.y.z<b></td></tr>
</table>
<div>
<a href="http://localhost:8080/jsp/examfolder/exam.jsp">Click here to go back</a>
</body>
</html>
<%}else{%>
<html>
<head><title>Online Examination<?title>
<script language="javascript">
fuction validation(Form_obj)
{
if(Form_obj.Seat_no.value.length==0)
{
alert("Please fill up thSeat Number");
Form_obj.Seat_no.focus();
return false;
}
if(Form_obj.Name.value.length==0)
{
alert("Please fill up the Name");
Form_obj.Name.focus();
return false;
}
return true;
23
}
</script>
</head>
<body dgcolor=lightgreen>
<center>
<h1>Online examination</h1>
</center>
<form action="Exam.jsp" method="post"
name="entry" onsubmit="return validation(this)">
<input type="hidden" value="list" name="action">
<table>
<tr>
<td><h3>Seat Number:</h3></td>
<td><input type="text" name="Seat_no"></td>
</tr>
<tr>
<td><h3>Name:</h3></td>
<td><input type="text" name="Name" size=50></td>
</tr>
<tr>
<td><h3>Total marks:10(Each question carries equal marks)</h3></td>
<td></td><td></td><td></td><td><b>Time:15 min</b></td>
</tr>
</table>
<hr/>
<b>1.
</b></br>
<input type="radio" name="group1" value="True">True
<input type="radio" name="group1" value="False">False
<br/>
<b>2.
</b></br>
<input type="radio" name="group2" value="True">True
<input type="radio" name="group2" value="False">False
<br/>
<b>3.
</b></br>
<input type="radio" name="group3" value="True">True
<input type="radio" name="group3" value="False">False
<br/>
<b>4.
</b></br>
<input type="radio" name="group4" value="True">True
<input type="radio" name="group4" value="False">False
<br/>
<b>5.
</b></br>
<input type="radio" name="group5" value="True">True
24
<input type="radio" name="group5" value="False">False
<br/>
<hr/>
<center>
<input type="submit" value="Submit">
<input type="reset" value="Clear"><br><br>
</center>
</form>
<%}%>

25
Ex No: 7 PROGRAM USING XML SCHEMA

Aim:

Develop a program using XML-Schema-XSLT/XSL

Algorithm:

 The xsl: output specifies how to display the result tree.

 The XSL processor produces the output result tree.

 It should be specified by xsl: output element.

 The method attributes of xsl: output specifies the overall


Process to produce the result tree.

 The HTML output method results tree as HTML document.

Program code:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html>
<body>
<h2>Students database</h2>
<table border="1">
<tr bgcolor="pink">
<th>Name</th>
<th>Address</th>
<th>Standard</th>
<th>Marks</th>
</tr>
<xsl:for-each select="Student/Person-Details">
<tr bgcolor="red">
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="address"/></td>
<td><xsl:value-of select="std"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

26
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="SimpleXml.xsl"?>
<Student>
<Person-Details>
<name>a</name>
<address>Pune</address>
<std>second</std>
<marks>70 percent</marks>
</Person-Details>
<Person-Details>
<name>b</name>
<address>chennai</address>
<std>third</std>
<marks>80 percent</marks>
</Person-Details>
<Person-Details>
<name>c</name>
<address>Mumbai</address>
<std>Forth</std>
<marks>77 percent</marks>
</Person-Details>
<Person-Details>
<name>d</name>
<address>delhi</address>
<std>second</std>
<marks>75 percent</marks>
</Person-Details>
</Student>

27
Ex No: 8 PROGRAM USING AJAX

Aim:

Develop a enterprises program using AJAX

Algorithm:

 Use JavaScript to initialize the XML HTML request object

 Use HTML to create areas for user input and output

 Use JavaScript to send the user input to a server

 Process the data on a server

 Use JavaScript to process any response from the server and display the result

28
Ex No: 9 PROGRAM USING DOM

Aim:

Develop a program using DOM.

Algorithm:
 Read the XML document.
 Select parser wrapper by name.
 Locate the elements by name.
 Read the node one by one.
 Display the names.

Program code:
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class read_element
{
static public void main(String arg[])
{
try{
System.out.println("Enter the name of XML document");
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String filename=input.readLine();
File fp=new File(filename);
if(fp.exists())
{DocumentBuilderFactory factory_obj=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory_obj.newDocumentBuilder();
Document doc=builder.parse(filename);
NodeList temp_list=doc.getElementsByTagName("*");
System.out.println("\nFollowing are the Elements in "+filename);
for(int i=0;i<temp_list.getLength();i++)
{
Element E=(Element)temp_list.item(i);
System.out.println("\t"+E.getNodeName());
}}
else{
System.out.println("File not found");
}}
catch(Exception e)
{}}
29
}

student.xml
<?xml version="1.0"?>
<student>
<Roll_No>5259</Roll_No>
<Personal_Info>
<Name>Nila</Name>
<Address>Kanyakumari</Address>
<Phone>9005808656</Phone>
</Personal_Info>
<Class>Third year</Class>
<Subject>Maths</Subject>
<Marks>191</Marks>
</student>

30
Ex No: 10 PROGRAM USING SAX

Aim:

Develop a program using SAX.

Algorithm:

 Read the XML document.


 Create a custom object model.
 Create a SAX parser.
 Create a document handler.
 Read the content and display it.

Program code:
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class readcontent{
public static void main (String argv []){
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("book.xml")); // normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName()); NodeList
listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons); for(int s=0; s<listOfPersons.getLength() ; s++){
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0); NodeList textFNList =
firstNameElement.getChildNodes();
System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");

31
Element lastNameElement = (Element)lastNameList.item(0); NodeList textLNList =
lastNameElement.getChildNodes();
System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0); NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());
}//end of if clause
}//end of for loop with s var
}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ()); }catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace (); }catch (Throwable t) {
t.printStackTrace ();
}
}//end of main
}

book.xml
<?xml version="1.0"?>
<student>
<person>
<first>Kiran</first>
<last>Pai</last>
<age>22</age>
</person>
<person>
<first>Bill</first>
<last>Gates</last>
<age>46</age>
</person>
<person>
<first>Steve</first>
<last>Jobs</last>
<age>40</age>
</person>
</student>

32
33

You might also like