0% found this document useful (0 votes)
8 views48 pages

XML notes

XML (Extensible Markup Language) is a markup language used for storing and organizing data with self-descriptive tags, making it extensible and a public standard. It has various applications, including web publishing, e-business, and metadata expression, and is structured using elements, attributes, and document type definitions (DTD). XML schemas enhance the capabilities of XML by specifying the structure and data types of XML documents, addressing limitations of DTDs.

Uploaded by

Roopa Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views48 pages

XML notes

XML (Extensible Markup Language) is a markup language used for storing and organizing data with self-descriptive tags, making it extensible and a public standard. It has various applications, including web publishing, e-business, and metadata expression, and is structured using elements, attributes, and document type definitions (DTD). XML schemas enhance the capabilities of XML by specifying the structure and data types of XML documents, addressing limitations of DTDs.

Uploaded by

Roopa Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

XML

Studocu is not sponsored or endorsed by any college or university

Downloaded by Roopa Sk
Introduction
XML stands for Extensible Markup Language. It is a text-based markup language derived
from Standard Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than specifying
how to display it like HTML tags, which are used to display the data.
There are three important characteristics of XML that make it useful in a variety of systems
and solutions −
XML is extensible − XML allows you to create your own self-descriptive tags, or language,
that suits your application.
XML carries the data, does not present it − XML allows you to store the data irrespective
of how it will be presented.
XML is a public standard − XML was developed by an organization called the World Wide
Web Consortium (W3C) and is available as an open standard.
Uses of XML
XML has a variety of uses for Web, e-business, and portable applications.
The following are some of the many applications for which XML is useful:
Web publishing: XML allows you to create interactive pages, allows the customer to
customize those pages, and makes creating e-commerce applications more intuitive. With
XML, you store the data once and then render that content for different viewers or devices
based on style sheet processing using an Extensible Style Language (XSL)/XSL
Transformation (XSLT) processor.
Web searching and automating Web tasks: XML defines the type of information contained
in a document, making it easier to return useful results when searching the Web:
General applications: XML provides a standard method to access information, making it
easier for applications and devices of all kinds to use, store, transmit, and display data.
e-business applications: XML implementations make electronic data interchange (EDI)
more accessible for information interchange, business-to-business transactions, and business-
to- consumer transactions.
Metadata applications: XML makes it easier to express metadata in a portable, reusable
format.
Pervasive computing: XML provides portable and structured information types for display
on pervasive (wireless) computing devices such as personal digital assistants (PDAs),
cellular

Downloaded by Roopa Sk
phones, and others. For example, WML (Wireless Markup Language) and VoiceXML are
currently evolving standards for describing visual and speech-driven wireless device interfaces.

The Syntax of XML


All XML documents begin with an XML declaration. The XML declaration identifies the
document as XML and provides the version number of the XML standard used. It may also
specify an encoding standard.
Comments in XML are the same as in HTML.
<!--comment -->
XML names are used to name elements and attributes. An XML name must begin with a
letter or an underscore and can include digits, hyphens, and periods.
XML names are case sensitive, so Body, body, and BODY are all distinct names. There is no
length limitation for XML names.
Every XML document defines a single root element, whose opening tag must appear on the
first line of XML code. All other elements of an XML document must be nested inside the
root element.
Every XML element that can have content must have a closing tag. Elements that do not
include content must use a tag with the following form: <element_name />
XML tags can have attributes, which are specified with name-value assignments. All attribute
values must be enclosed by either single or double quotation marks.
example:
<?xml version = "1.0" encoding = "utf-8"?>
<ad>
<year> 1960 </year>
<make> Cessna </make>
<model> Centurian </model>
<color> Yellow with white trim </color>
<location>
<city> Gulfport </city>
<state> Mississippi </state>
</location>
</ad>
Some characters are reserved by the XML syntax itself. Hence, they cannot be used directly.
To use them, some replacement-entities are used, which are listed below 3

Downloaded by Roopa Sk
Not Allowed Replacement Character
Character Entity Description
< &lt; less than
> &gt; greater than
& &amp; Ampersand
' &apos; Apostrophe
" &quot; quotation
mark

XML Document Structure


An XML document often uses two auxiliary files:
 One to specify the structural syntactic rules ( DTD / XML schema)
 One to provide a style specification to describe how the content of the
document to be printed ( CSS/XSLT Style Sheets)
XML document schema can be used to constrain what information can be stored and the data
types of stored values .
There are two mechanism for specifying Schemas in XML:
 Document Type Definition(DTD).
 XML Schema.
Document Type Definition (DTD)
 A document type definition (DTD) is a set of structural rules called declarations,
which specify a set of elements that can appear in the document as well as how and
where these elements may appear.
A DTD is primarily a list of rules for what pattern of sub elements may appear within an
element.
A document can be texted against the DTD to determine whether it conforms to the rules the
DTD describes.
Types of DTD:
Internal DTD: A DTD can be embedded in the XML document whose syntax rules it
describes. External DTD: The DTD can be stored in a file separate from the XML document.
Declaring Elements
A DTD describes the syntactic structure of a particular set of documents.
Each element declaration in a DTD specifies the structure of one category of elements.
The declaration provides the name of the element whose structure is being defined, along
with the specification of the structure of that element.

Downloaded by Roopa Sk
The form of an element declaration for elements that contain elements is as follows:
<! ELEMENT element_name (list of names of child elements) >
Sub elements can be specified as:
<! ELEMENT element_name (#PCDATA) - (i.e parsed character data/string)
Example:
<! ELEMENT department (dept_name, building, budget) >
<! ELEMENT dept_name (#PCDATA) >
<! ELEMENT building (#PCDATA) >
<! ELEMENT budget (#PCDATA) >

In many cases, it is necessary to specify the number of times that a sub element may appear.
This can be done in a DTD declaration by adding a modifier to the sub element specification.
Modifier meaning
+ one or more occurrence
* Zero or more occurrence
? Zero or one occurrence
Example: <!ELEMENT person (parent+, age, spouse?, sibling*)>
In this example, a person element is specified to have the following children elements: one or
more parent elements, one age element, possibly a spouse element, and zero or more sibling
elements.
Attribute Declaration
An attribute declaration must include the name of the element to which the attribute belongs,
the attribute9s name, and its type. Also, it may include a default value.
The general form of an attribute declaration is as follows:
<!ATTLIST element,name attribute_name attribute type [default_value\>
If more than one attribute is declared for a given element, the
declarations can be combined, as in the following example:
<!ATTLIS T element_name
attribute _name_1 attribute type default_value_1
attribute_name_2 attribute_type default_value_2
attribute_name_n attribute_type default_value_n>
possible default values for attributes are:

Downloaded by Roopa Sk
Value Meaning
A value This is the value used if none is specified in an element.
#FIXED value The value which every element will have and which cannot be changed.
#REQUIRED No default value is given; every instance of the element must specify a
value.
#IMPLIED the value may or may not be specified in an element
Declaring Entities
Entities can be defined so that they can be referenced anywhere in the content of an XML
document.
Entities can also be defined so that they can be referenced only in DTDs.
The form of an entity declaration that appears in a DTD follows:
<!ENTITY entity_name " entity_value" >
example of an entity: Suppose that a document includes a large number of references to the
full name of President Kennedy.
You could define an entity to represent his complete name as follows:
<!ENTITY jfk "John Fitzgerald Kennedy">
Any XML document that uses a DTD that includes this declaration can specify the complete
name with just the reference jfk.
Sample DTD---planes.dtd
<?xml version = "1.0" encoding = "utf-8"?>
<!4 planes.dtd - a document type definition for the planes.xml document, which specifies
a list of used airplanes for sale 4>
<!ELEMENT planes_for_sale (ad+)>
<!ELEMENT ad (year, make, model, color, description, price?, seller, location)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT make (#PCDATA)>
<9ELEMENT model (#PCDATA)>
<!ELEMENT color (#PCDATA)>
<!ELEMENT description (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT seller (#PCDATA)>
<!ELEMENT location (city, state)>

Downloaded by Roopa Sk
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ATTLIST seller phone CDATA #REQUIRED>
<!ATTLIST seller email CDATA #IMPLIED>
<!ENTITY c "Cessna">
<!ENTITY p "Piper">
<!ENTITY b "Beechcraft">
The following is an xml document which conforms to planes.dtd
<?xml version = "1.0" encoding = "utf-8"?>
<!4 planes.xml - ->
<!DOCTYPE planes_for_sale SYSTEM <planes.dtd=>
<planes_for_sale>
<ad>
<year>1977</year>
<make>dc;</make>
<model>Skyhawk</model>
<color>blue and white</color>
<description>newly painted and in good condition</description>
<price>2000000</price>
<seller phone==123-4566-7890=>Skyway aircraft</seller>
<location>
<city>hyd</city>
<state>TS </state>
</location>
</ad>
</ planes_for_sale >

Internal and External DTDs


DTD can appear inside an XML document or in an external file.

Downloaded by Roopa Sk
 If the DTD is included in the XML code, it must be introduced with
<! DOCTYPE root_name [ and terminated with ]> -- Internal DTD
 When the DTD is in its own file, the XML document refers to it with a DOCTYPE
declaration as its second line. This declaration has the following form:
<! DOCTYPE XML_document_root_name SYSTEM "DTD_file_name">--External DTD
XML Namespace
An XML namespace is a collection of element and attribute names used in XML documents.
The name of a namespace usually has the form of a URI.

A namespace declaration for an element is given as the value of the xmlns attribute, as in the
following:

<element_name xmlns [ :prefix] = URI>


The square brackets here indicate that what is within them is optional.
The prefix, if included, is the name that must be attached to the names in the declared
namespace. If the prefix is not included, the namespace is the default for the document.
A prefix is used for two reasons. First, most URIs are too long to be typed on every
occurrence of every name from the namespace.
Second, a URI includes characters that are invalid in XML.
As an example of a prefixed namespace declaration, consider the following:
<birds xmlns:bd = "http://www.audubon.org/names/species">
Within the birds element, including all of its children elements, the names from the given
namespace must be prefixed with bd, as in the following element:
<bd:lark>

If an element has more than one namespace declaration, they are declared as in the following
example:
The first is declared to be the default namespace; the second defines the prefix, cap:
<states>
xmlns = "http://www.states-info.org/states"
xmlns:cap = "http://www.states-info.org/state-capitals"
<state>
<name> South Dakota </name>
<population> 754844 </population>
<capital>
<cap:name> Pierre </cap:name>
<cap:population> 12429 </cap:population>
</capital>
</state>
</states>

Downloaded by Roopa Sk
XML SCHEMAS

An XML schema is an XML document so it can be parsed with an XML parser.


Schema Fundamentals:
• Schema are related idea of class and an object in an OOP language. A Schema is
similar to a class definition an XML document that conforms to a specific schema are
considered instances of that schema or object of the schema9s class.
• Schemas have three primary purposes
- Specify elements and attributes of an XML language
- Specify the structure of its instance XML documents including where and how
often the elements may appear.
- Specify the data type of every element in its instance XML documents .
Disadvantages of DTD compared to XML schema
• Cannot be parsed by an XML parser
• All declarations in DTD are global (impossible to define two elements with same
name.)
• DTD cannot control what kind of information a given element or
attribute can contain.

Defining a schema:
Schemas are written from a namespace(schema of schemas): The name of this namespace
is
http://www.w3.org/2001/XMLSchema
element, schema, sequence and string are some names from this namespace Every XML
schema has a single root, schema.

• The schema element must specify the namespace for the schema of schemas from
which the schema8s elements and its attributes will be drawn. It often specifies a prefix
that will be used for the names in the schema. This name space specification appears as
xmlns:xsd = http://www.w3.org/2001/XMLSchema
Every XML schema itself defines a tag set like DTD, which must be named with the
targetNamespace attribute of schema element. The target namespace is specified by
assigining a name space to the target namespace attribute as the following:
targetNamespace = http://cs.uccs.edu/planeSchema
Every top-level element places its name in the target namespace If we want to include

Downloaded by Roopa Sk
nested elements(ie if the names of the elements and attributes that are not defined
directly in the schema element), we must set the elementFormDefault attribute to
qualified.
elementFormDefault = <qualified=
The default namespace which is source of the unprefixed names in
the schema is given with another xmlnsspecification without the
prefix.
xmlns = "http://cs.uccs.edu/planeSchema <
Complete example of opening tag of Schema Element
<xsd:schema
<!-- Namespace for the schema itself -->
xmlns:xsd = http://www.w3.org/2001/XMLSchema

<!--Namespace where elements defined here will be placed -->

targetNamespace = http://cs.uccs.edu/planeSchema
<!-- Default namespace for this document -->
xmlns = http://cs.uccs.edu/planeSchema.
<!-- Specify non-top-level elements to be in the target namespace-->
elementFormDefault = "qualified= >
One alternative to the preceding opening tag would be to make the XMLSchema names
the default so that they do not need to be prefixed in the schema. Then the names in the
target namespace would need to be prefixed. The following schema tag illustrates this
approach:

Defining a schema instance:


An instance of schema must specify the namespaces it uses. These specifications are given
as attribute assignments in the tag for its root element
1. Define the default namespace
- if the root element is planes
<planes xmlns = http://cs.uccs.edu/planeSchema…>
2. The second attribute specification in the root element of an instance document is

Downloaded by Roopa Sk
for the schemaLocation attribute. This attribute is used to name the standard
namespace for instances which includes the name XMLSchema-instance
.(XMLSchema-instance)
xmlns:xsi ==http://www.w3.org/2001/XMLSchema-instance"
3. Specify location where the default namespace is defined, using the schemaLocation
attribute, which is assigned two values namespace and filename.
xsi:schemaLocation ="http://cs.uccs.edu/planeSchema planes.xsd" > Altogether,
the opening root tag of an XML instance of the planes.xsd schema, where the root
element name in the instance is planes, could appear as follows:

Downloaded by Roopa Sk
Schema Data types
Two categories of user-defined schema data types :
1. Simple data type is a data type whose content is restricted to strings only, no attributes
and no nested elements(child elements) .It is possible to add restrictions(facets) to a
datatype inorder to limit its content .
2. Complex datatype can have attributes and nested elements.

• XML Schema defines 44 data types .19 of which are primitive and 25 of which are
derived.
• Primitive datatype: string, Boolean, float, time …
• Predefined Derived datatype: Examples byte, decimal, positiveInteger,.
• User-defined derived data types 3 These datatypes are defined by specifying
restrictions on an existing type,which is then called a basetype. Such user defined types
are derived types. Constraints on derived types are given in terms of facets of the base
type .Ex: interget data type has 8 possible facets : totalDigits,
maxInclusive,,maxExclusive etc.
- Both simple and complex types can be either named or anonymous .
DTDs define global elements (context of reference is irrelevant). But context of reference
is essential in XML schema
Data declarations in an XML schema can be
1. Local ,which appears inside an element that is a child of schema
2. Global, which appears as a child of schema
Defining a simple type:

• Elements are defined in an XML schema with the element tag, which is from the
XMLSchema namespace. Recall that the prefix xsd is normally used for names from this
namespace. Use the element tag and set the nameand typeattributes
<xsd:element name = "bird= type
= "xsd:string= /> The instance
could be :
<bird> Yellow-bellied sap sucker </bird>
• An element can be given default value using default attribute. Default value
is automatically assigned to the element when no other value is specified.
<xsd:element name = "bird= type = "xsd:string= default==Eagle= />

Downloaded by Roopa Sk
• An element can have constant value, using fixed attribute. A fixed value is
automatically assigned to the element , and we cannot specify another value.
<xsd:element name = "bird= type = "xsd:string= fixed==Eagle= />
Declaring User-Defined Types:
• User-Define type is described in a simpleType element, using facets . facets must be
specified in the content of restrictionelement. Restrictons on XML elements are called
facets. Restrictions are used to define acceptable values for XML elements or
attributes. Facets values are specified with the valueattribute.

For example, the following declares a user-defined type , firstName


<xsd:simpleType name = <firstName" >
<xsd:restriction base = "xsd:string" >
<xsd:maxLength value = "20" />
</xsd:restriction>
</xsd:simpleType>
The length facet is used to restrict the string to an exact number of characters. The
minLength facet is used to specify a minimum length.
<xsd:simpleType name = <phoneNumber" >
<xsd:restriction base = "xsd:decimal" >
<xsd:precision value = <10" />
</xsd:restriction>
</xsd:simpleType>
Declaring Complex Types:
• There are several categories of complex types, but we discuss just one, element-only
elements which can have elements in their content, but no text. Element-only elements
are defined with the complexTypetag.
• The sequencetag is used to contain an ordered group of elements.
• Use the alltag if the order is not important .
• Nested elements can include attributes that give the allowed number of
occurrences (minOccurs, maxOccurs, unbounded)
• For ex:
<xsd:complexType name = "sports_car" >
<xsd:sequence>
<xsd:element name = "make= type = "xsd:string" />

Downloaded by Roopa Sk
<xsd:element name = "model= type = "xsd:string" />
<xsd:element name = "engine= type = "xsd:string" />
<xsd:element name = "year= type = "xsd:decimal" />
</xsd:sequence>
</xsd:complex
Type>
Example 1:

Schema definition document

Schema Instance Docume

Downloaded by Roopa Sk
Validating Instances of Schemas:
An XML schema provides a definition of a category of XML documents. However,
developing a schema is of limited value unless there is some mechanical way to
determine whether a given XML instance document confirms to the schema. Several
XML schema validation tools are available eg. xsv(XML schema validator) This can be
used to validate online. Output of xsv is an XML document. When run from command
line output appears without being formated.
If schema is not in the correct format, the validator will report that it could not find the
specified schema.

DISPLAYING RAW XML DOCUMENTS

An XML enabled browser or any other system that can deal with XML documents
cannot possibly know how to format the tags defined in the xml documents. Without a
style sheet that defines presentation styles for the document tags the XML documents
cannot be displayed in a formatted manner. Most contemporary browsers like FX3 have
default style sheets that are used when style sheets are not defined for xml documents.

Downloaded by Roopa Sk
//mail.xml
<?xml version="1.0"?>
<mail>
<to>Rani</to>
<from>Ravi</from>
<heading>Remainder</heading>
<body>
<title>Dear Sister</title>
<wish>Good Morning to you</wish>
<msg>Please dont forget about our parents Wedding Anniversary
today.Be there in
time</msg>
</body>
</mail>
Raw xml document mail.xml

Some of the elements in the display are preceded by dashes. These elements can be
elided (temporarily suppressed) by placing the mouse cursor over the dash and clicking
the left mouse button. For example, if the mouse cursor is placed over the dash to the left
of the first<ad> tag and the left mouse button is clicked, the result is as shown below.

Downloaded by Roopa Sk
6. DISPLAYING XML DOCUMENTS WITH CSS
Style sheet information can be provided to the browser for an xml document in
two ways.

 First, a CSS file that has style information for the elements in the XML document
can be developed.

 Second the XSLT style sheet technology can be used. Using CSS is effective,
XSLT provides far more power over the appearance of the documents display.

A CSS style sheet for an XML document is just a list of its tags and associated styles. The
connection of an XML document and its style sheet is made through an xmlstylesheet
processing instruction. Displayis used to specify whether an element is to be displayed
inline or in a separate block.
<?xml-stylesheet type = "text/css= href = <planes.css"?>

For example: planes.css


ad { display: block; margin-top: 15px; color: blue;}
year, make, model { color: red; font-size: 26pt;}
color {display: block; margin-left: 20px; font-size: 12pt;}
description {display: block;color: green; margin-left: 20px; font-size: 10pt;}

seller { display: block; margin-left: 15px; font-size: 14pt;}

location {display: block; color: cyan;margin-left: 40px; }

city {font-size: 12pt;}

state {font-size: 12pt;}

planes.dtd document
<!ELEMENT planes_for_sale (ad+)>
<!ELEMENT ad (year, make, model, color, description, price?, seller, location)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT make (#PCDATA)>
<!ELEMENT model (#PCDATA)>

Downloaded by Roopa Sk
<!ELEMENT color (#PCDATA)>
<!ELEMENT description (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT seller (#PCDATA)>
<!ELEMENT location (city, state)>
<!ELEMENT city (#PCDATA)>
<!ELEMENT state (#PCDATA)>
<!ATTLIST seller phone CDATA #REQUIRED>
<!ATTLIST seller email CDATA #IMPLIED>
<!ENTITY c "Cessna">
<!ENTITY p "Piper">
<!ENTITY b "Beechcraft">

Planes.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE planes_for_sale SYSTEM "planes.dtd">
<planes_for_sale>
<ad>
<year> 1977 </year>
<make> &c; </make>
<model> Skyhawk </model>
<color> Light blue and white </color>
<description> New paint, nearly new interior,
685 hours SMOH, full IFR King avionics </description>
<price> 23,495 </price>
<seller phone = "555-222-3333"> Skyway Aircraft </seller>
<location>
<city> Rapid City, </city>
<state> South Dakota </state>
</location>
</ad>
</planes_for_sale>

Downloaded by Roopa Sk
With planes.css the display of planes.xml as following:

Downloaded by Roopa Sk
EXTENSIBLE STYLE SHEET LANGUAGE (XSL)
A family of specifications for transforming XML documents. It consist of three
standards:

XSLT: specifies how to transform documents(xml to html)

Xpath: identify parts of xml documents, such as specific elements that are in
specific positions in the document or element that have particular attribute values.

XSL-FO: is used to generate high quality printable documents in formats such as


PDF etc.

Together they provide powerful means of formatting xml documents.

XSLT describes how to transform XML documents into different form or formats
such as HTML
,Plain text etc.

Overview of XSLT

XSLT processors take both an XML document and an XSLT document as input.
The XSLT document is the program to be executed; the XML document is the input data
to the program. Parts of the XML document are selected, possibly modified, and merged
with parts of the XSLT document to form a new document, which is sometimes called an
XSL document. Note that the XSL document is also an XML document, which could be
again the input to an XSLT processor. The output document can be stored for future
use by applications, or it may be immediately displayed by an application, often a
browser. Neither the XSLT document nor the input XML document is changed by the
XSLT processor.

Figure: XSLT processing

Downloaded by Roopa Sk
XSL Transformations for Presentation

XSLT includes more than 50 formatting object(element) types and more than 230
attributes, so it is a large and complex tag set.

Let9s suppose we have the following sample XML file, students.xml, which is required to be
transformed into a well-formatted HTML document.
students.xml
<?xml version = "1.0"?>
<class>
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
We need to define an XSLT style sheet document for the above XML document to meet the
following criteria −
 Page should have a title Students.
 Page should have a table of student details.
 Columns should have following headers: Roll No, First Name, Last Name, Nick
Name, Marks
 Table must contain details of the students accordingly.
Step 1: Create XSLT document
Create an XSLT document to meet the above requirements, name it as students.xsl and save
it in the same location where students.xml lies.

Downloaded by Roopa Sk
students.xsl
<?xml version = "1.0" encoding = "UTF-8"?>
<!-- xsl stylesheet declaration with xsl namespace:
Namespace tells the xlst processor about which
element is to be processed and which is used for output purpose only
-->
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<!-- xsl template declaration:
template tells the xlst processor about the section of xml
document which is to be formatted. It takes an XPath expression.
In our case, it is matching document root element and will
tell processor to process the entire document with this template.
-->
<xsl:template match = "/">
<!-- HTML tags
Used for formatting purpose. Processor will skip them and browser
will simply render them.
-->

<html>
<body>
<h2>Students</h2>

<table border = "1">


<tr bgcolor = "#9acd32">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>

<!-- for-each processing instruction


Looks for each element matching the XPath expression
-->

<xsl:for-each select="class/student">
<tr>
<td>
<!-- value-of processing instruction
process the value of the element matching the XPath expression
-->
<xsl:value-of select = "@rollno"/>
</td>

<td><xsl:value-of select = "firstname"/></td>


<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>

Downloaded by Roopa Sk
<td><xsl:value-of select = "marks"/></td>

</tr>
</xsl:for-each>

</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Step 2: Link the XSLT Document to the XML Document
Update student.xml document with the following xml-stylesheet tag. Set href value to
students.xsl
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
...
</class>

Step 3: View the XML Document in Internet Explorer


students.xml
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>
<class>
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>

Downloaded by Roopa Sk
Output

 <xsl:template> defines a way to reuse templates in order to generate the desired


output for nodes of a particular type/context.
Declaration
Following is the syntax declaration of <xsl:template> element.
<xsl:template
name = Qname
match = Pattern
priority = number
mode = QName >
</xsl:template>

 <xsl:value-of> tag puts the value of the selected node as per XPath expression, as text.
Declaration
Following is the syntax declaration of <xsl:value-of> element.
<xsl:value-of
select = Expression
disable-output-escaping = "yes" | "no" >
</xsl:value-of>

 <xsl:for-each> tag applies a template repeatedly for each node.


Declaration
Following is the syntax declaration of <xsl:for-each> element

Downloaded by Roopa Sk
<xsl:for-each
select = Expression >
</xsl:for-each>

XML PROCESSOR :

The Purposes of XML Processors


 First, the processor must check the basic syntax of the document for well-formedness.
 Second, the processor must replace all references to entities in an XML document with
their definitions.
 Third, elements in XML schemas can specify that their values in an XML document have
default values, which must be copied into the XML document during processing.
 Fourth, when an XML schema is specified and the processor includes a validating parser, the structure
of the XML document must be checked to ensure that it is legitimate.

The SAX Approach


The Simple API for XML (SAX) standard, which was released in May 1998, was developed by an
XML users group, XML-DEV. Although not developed or supported by any standards organization,
SAX has been widely accepted as a de facto standard and is now widely supported by XML
processors.
The SAX approach to processing is called event processing. The processor scans the XML
document from beginning to end. Every time a syntactic structure of the document is recognized, the
processor signals an event to the application by calling an event handler for the particular structure
that was found. The syntactic structures of interest naturally include opening tags, attributes, text, and
closing tags. The interfaces that describe the event handlers form the SAX API.

The DOM Approach


The natural alternative to the SAX approach to XML document parsing is to build a hierarchical
syntactic structure of the document. In the case of HTML, the browser parses the document and
builds the DOM tree. In the case of XML, the parser part of the XML processor builds the DOM tree.
In both cases, the nodes of the tree are represented as objects that can be accessed and processed or
modified by the application. When parsing is complete, the complete DOM representation of the
document is in memory and can be accessed in a number of different ways, including tree traversals
of various kinds as well as random accesses.

The DOM representation of an XML document has several advantages over the sequential listing
provided by SAX parsers. First, it has an obvious advantage if any part of the document must be
accessed more than once by the application. Second, if the application must perform any
rearrangement of the elements of the document, it can most easily be done if the whole document is
accessible at the same time. Third, accesses to random parts of the document are possible. Finally,
because the parser sees the whole document before any processing takes place, this approach avoids
any processing of a document that is later found to be invalid.
The process of building the DOM structure of an XML document requires some syntactic analysis
of the document, similar to that done by SAX parsers. In fact, most DOM parsers include a SAX
parser as a front end.

Downloaded by Roopa Sk
J2EE: exploring architecture styles, features of EE platform, web servers
and application servers

J2EE Architecture
- The client/server application architecture.
- Which was a two-tier architecture.
- Evolved over time to a multitier architecture.
- This natural progression occurred as additional tiers were introduced between the end-
user clients and back-end systems.
- Although a multitier architecture brings greater flexibility of design.
- It also increases the
o complexity of building,
o testing, deploying,
o administering, and
o maintaining application components.

Two-Tier Architecture
- The two-tier architecture is also known as the client/server architecture.
- It consists mainly of two tiers:
o data and
o client (GUI).
- The application logic can be located in either the client tier.
- Which results in a fat client or located in the data tier.
- which results in a fat server (see Figure).

Downloaded by Roopa Sk
[ Figure : Two-tier architecture. ]

- This type of architecture suffers from a lack of scalability.


- Because both the client and the server have limited resources.
- In addition to the negative effect of network traffic to transfer data to the fat client.
- Another issue is maintainability.
- We have to roll out the new system version to all system users.

Three-Tier Architecture
- To address the issues of the two-tier architecture, the application logic will be placed in
its own tier.
- Thus applications can be portioned into three tiers.
- The first tier is referred to as the presentation layer, and consists of the application GUI.
- The middle tier, or the business layer, consists of the business logic to retrieve data for
the user requests.
- The back-end tier, or data layer, consists of the data needed by the application.
- Figure illustrates the three-tier architecture.

Downloaded by Roopa Sk
[ Figure : Three-tier architecture. ]

- The decoupling of application logic from either presentation or data increases


the flexibility of the application design.
- Multiple views or a GUI can be added without changing the existing application logic.
- Similarly, multiple applications can be created using the same data model.
- Changing the components of one tier should not impact the other two tiers.
- For example, any change to the data or GUI will not affect the application logic.

Note :- 1
- The three-tier architecture is the basis for J2EE applications.
- In which EJBs provide a mechanism to build application logic.
- While JSPs and servlets abstract the presentation layer and allow interaction with
the business layer.
- One important feature of the three-tier architecture is sharing system resources by
all clients.
- Which results in :
o highly efficient,
o scalable,
o secure, and
o reliable applications.

Downloaded by Roopa Sk
Multitier J2EE Architecture
- Multitier (or n-tier) architecture differs from the three-tier architecture in viewing each
tier logically.
- Rather than physically.
- The application logic, for example, can be split into more than one layer; the
business logic tier and the presentation logic tier.
- Similarly, the user interface is partitioned into the client tier and the presentation tier.
- A multitier architecture determines where the software components that make up a
computing system are executed in relation to each other and to the hardware, network,
and users.
- J2EE is a multitier architecture, which partitions the application into client,
o presentation logic,
o business logic, and
o enterprise information tiers.

Note : - 2
- The J2EE platform is designed not only to support a multitier architecture to
partition applications.
- But also to provide infrastructure common services to reduce the complexity
of developing and deploying these applications.
- Other than multitier, the J2EE architecture provides the enterprise with
common infrastructure services.
- Which help in developing and deploying :
o portable,
o secure and
o transactional applications.

- The J2EE architecture partitions enterprise applications into three fundamental parts:
o components,
o containers, and
o connectors.

Downloaded by Roopa Sk
- Components are the key focus of application developers.
- Whereas system vendors implement containers and
- Connectors to hide complexity and enhance portability.
- Enterprise Java applications can run on any J2EE-compliant application server.

Note :- 3
- Multitier distributed applications follow the Model-View-Controller (MVC) paradigm,.
- This design pattern provides clean separation between tiers.
- Using this paradigm, the model (data tier) is separated from the view (client
and presentation tiers).
- Similarly, the controller (the application logic tier) is separated from both the view and
the model.
- Containers transparently provide common services :
o including transaction,
o security,
o persistence, and
o resource pooling, to both clients and components.

- A container allows the configuration of applications.


- And components at deployment.
- Rather than hard-coding them in program code.
- Connectors extend the J2EE platform.
- By defining a portable client service API to plug into existing enterprise vendor products.
- Connectors promote flexibility by enabling a variety of implementations of
specific services.

Features Java EE

The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is
currently known as Jakarta EE. It is a set of specifications wrapping around Java SE
(Standard Edition). The Java EE provides a platform for developers with enterprise features
such as distributed computing and web services. Java EE applications are usually run on
reference run

Downloaded by Roopa Sk
times such as microservers or application servers. Examples of some contexts where Java
EE is used are e-commerce, accounting, banking information systems.

Specifications of Java EE

Java EE has several specifications which are useful in making web pages, reading and writing
from database in a transactional way, managing distributed queues. The Java EE contains
several APIs which have the functionalities of base Java SE APIs such as Enterprise
JavaBeans, connectors, Servlets, Java Server Pages and several web service technologies.

1. Web Specifications of Java EE


o Servlet- This specification defines how you can manage HTTP requests either in a
synchronous or asynchronous way. It is low level, and other specifications depend on
it
o WebSocket- WebSocket is a computer communication protocol, and this API
provides a set of APIs to facilitate WebSocket connections.
o Java Server Faces- It is a service which helps in building GUI out of components.
o Unified Expression Language- It is a simple language which was designed to facilitate
web application developers.

2. Web Service Specifications of Java EE


o Java API for RESTful Web Services- It helps in providing services having
Representational State Transfer schema.
o Java API for JSON Processing- It is a set of specifications to manage the information
provided in JSON format.

Downloaded by Roopa Sk
o Java API for JSON Binding- It is a set of specifications provide for binding or parsing
a JSON file into Java classes.
o Java Architecture for XML Binding- It allows binding of xml into Java objects.
o Java API for XML Web Services- SOAP is an xml based protocol to access web
services over http. This API allows you to create SOAP web services.

3. Enterprise Specifications of Java EE


o Contexts and Dependency Injection- It provides a container to inject dependencies as
in Swing.
o Enterprise JavaBean- It is a set of lightweight APIs that an object container possesses
in order to provide transactions, remote procedure calls, and concurrency control.
o Java Persistence API- These are the specifications of object-relational mapping
between relational database tables and Java classes.
o Java Transaction API- It contains the interfaces and annotations to establish
interaction between transaction support offered by Java EE. The APIs in this abstract
from low- level details and the interfaces are also considered low-level.
o Java Message Service- It provides a common way to Java program to create, send and
read enterprise messaging system's messages.

4. Other Specifications of Java EE


o Validation- This package contains various interfaces and annotations for declarative
validation support offered by Bean Validation API.
o Batch applications- It provides the means to run long running background tasks which
involve a large volume of data and which need to be periodically executed.
o Java EE Connector Architecture- This is a Java-based technological solution for
connecting Java servers to Enterprise Information System.

Server: Web vs. Application

Server is a device or a computer program that accepts and responds to the request made by other
program, known as client. It is used to manage the network resources and for running the
program or software that provides services.

There are two types of servers:

1. Web Server
2. Application Server

Web Server

Downloaded by Roopa Sk
Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf
etc. It can't be used for EJB.

It is a computer where the web content can be stored. In general web server can be used to
host the web sites but there also used some other web servers also such as FTP, email,
storage, gaming etc.

Examples of Web Servers are: Apache Tomcat and Resin.

Web Server Working

It can respond to the client request in either of the following two possible ways:

o Generating response by using the script and communicating with database.


o Sending file to the client associated with the requested

URL. The block diagram representation of Web Server is shown

below:

Important points

o If the requested web page at the client side is not found, then web server will sends
the HTTP response: Error 404 Not found.
o When the web server searching the requested page if requested page is found then it
will send to the client with an HTTP response.
o If the client requests some other resources then web server will contact to application
server and data is store for constructing the HTTP response.

Downloaded by Roopa Sk
Application Server

Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb
etc. It is a component based product that lies in the middle-tier of a server centric architecture.

It provides the middleware services for state maintenance and security, along with persistence
and data access. It is a type of server designed to install, operate and host associated services
and applications for the IT services, end users and organizations.

The block diagram representation of Application Server is shown below:

The Example of Application Servers are:

1. JBoss: Open-source server from JBoss community.


2. Glassfish: Provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic: Provided by Oracle. It more secured.
4. Websphere: Provided by IBM.

Downloaded by Roopa Sk
Database programming with JDBC: JDBC Drivers, processes with java.sql package

JDBC Driver

JDBC Driver is a software component that enables java application to interact with the database.

There are 4 types of JDBC drivers:


1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.

Downloaded by Roopa Sk
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls
i native calls of the database API. It is not written entirely in java.

Downloaded by Roopa Sk
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Downloaded by Roopa Sk
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.

Downloaded by Roopa Sk
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.

Disadvantage:
o Drivers depend on the Database.

There are 5 steps to connect any java application with the database using JDBC.

1) Register the driver class


2) Create connection
3) Create statement
4) Execute queries
5) Close

connection JDBC

Database Access

Downloaded by Roopa Sk
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically
load the driver class.

Syntax of forName() method


1. public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

1. Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method


1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException
Example to establish connection with the Oracle database
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.

Syntax of createStatement() method


1. public Statement createStatement()throws SQLException
Example to create the statement object
1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Downloaded by Roopa Sk
Syntax of executeQuery() method
1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.

Syntax of close() method


1. public void close()throws SQLException
Example to close connection
1. con.close();

Exploring JDBC using java.sql

JDBC was designed to keep simple things simple. This means that the JDBC
API makes everyday database tasks, like simple SELECT statements, very
easy.
Import a package java.sql.* : This package provides you set of all classes that
enables a network interface between the front end and back end database.
• DriverManager will create a Connectionobject.
• java.sql.Connection interface represents a connection with a specific
database. Methods of connection is close(), creatStatement(),
prepareStatement(), commit(), close() and prepareCall()
• Statement interface used to interact with database via the execution of SQL
statements. Methods of this interface are executeQuery(), executeUpdate(),
execute() and getResultSet().
• A ResultSet is returned when you execute an SQL statement. It maintains a
pointer to a row within the tablur results. Mehods of this interface are next(),
getBoolean(), getByte(), getDouble(), getString() close() and getInt().

Connection interface

Downloaded by Roopa Sk
A Connection is a session between a Java application and a database. It helps to establish a
connection with the database.

The Connection interface is a factory of Statement, PreparedStatement, and


DatabaseMetaData, i.e., an object of Connection can be used to get the object of Statement
and DatabaseMetaData. The Connection interface provide many methods for transaction
management like commit(), rollback(), setAutoCommit(), setTransactionIsolation(), etc.

Commonly used methods of Connection interface:

1) public Statement createStatement(): creates a statement object that can be used to


execute SQL queries.

2) public Statement createStatement(int resultSetType,int


resultSetConcurrency): Creates a Statement object that will generate ResultSet objects with
the given type and concurrency.s in Java

3) public void setAutoCommit(boolean status): is used to set the commit status. By default,
it is true.

4) public void commit(): saves the changes made since the previous commit/rollback is
permanent.

5) public void rollback(): Drops all changes made since the previous commit/rollback.

6) public void close(): closes the connection and Releases a JDBC resources immediately.

Statement interface

The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the object of
ResultSet.

Commonly used methods of Statement interface:

The important methods of Statement interface are as follows:

1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.

2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop,
insert, update, delete etc.

3) public boolean execute(String sql): is used to execute queries that may return multiple results.

Downloaded by Roopa Sk
4) public int[] executeBatch(): is used to execute batch of commands.

Example of Statement interface

Let9s see the simple example of Statement interface to insert, update and delete the record.

import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:
xe","system","oracle");
Statement stmt=con.createStatement();
//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 w
here id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}

PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute


parameterized query.

Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

Downloaded by Roopa Sk
How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of


PreparedStatement. Syntax:

public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

Method Description

public void setInt(int paramIndex, int sets the integer value to the given parameter
value) index.

public void setString(int paramIndex, sets the String value to the given parameter index.
String value)

public void setFloat(int paramIndex, sets the float value to the given parameter index.
float value)

public void setDouble(int paramIndex, sets the double value to the given parameter
double value) index.

public int executeUpdate() executes the query. It is used for create, drop,
insert, update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.

Java CallableStatement Interface

CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database by the use of stored procedures and functions that
will make the performance better because these are precompiled.

Suppose you need the get the age of the employee based on the date of birth, you may create a
function that receives date as the input and returns age of the employee as the output.

Downloaded by Roopa Sk
How to get the instance of CallableStatement?

The prepareCall() method of Connection interface returns the instance of CallableStatement.


Syntax is given below:

1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

The example to get the instance of CallableStatement is given below:

1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

ResultSet interface

The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row.

But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as updatable by:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet. CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface


1) public boolean next(): is used to move the cursor to the one row next from the
current position.

2) public boolean previous(): is used to move the cursor to the one row previous from
the current position.

3) public boolean first(): is used to move the cursor to the first row in result set
object.

4) public boolean last(): is used to move the cursor to the last row in result set
object.

5) public boolean absolute(int is used to move the cursor to the specified row number
row): in the ResultSet object.

Downloaded by Roopa Sk
6) public boolean relative(int row): is used to move the cursor to the relative row number in
the ResultSet object, it may be positive or negative.

7) public int getInt(int is used to return the data of specified column index of
columnIndex): the current row as int.

8) public int getInt(String is used to return the data of specified column name of
columnName): the current row as int.

9) public String getString(int is used to return the data of specified column index of
columnIndex): the current row as String.

10) public String getString(String is used to return the data of specified column name of
columnName): the current row as String.

Java ResultSetMetaData Interface

The metadata means data about data i.e. we can get further information from the data.

If you have to get metadata of a table like total number of column, column name, column
type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata
from the ResultSet object.

Commonly used methods of ResultSetMetaData interface

Method Description

public int getColumnCount()throws SQLException it returns the total number of columns in


the ResultSet object.

public String getColumnName(int index)throws it returns the column name of the specified
SQLException column index.

public String getColumnTypeName(int it returns the column type name for the
index)throws SQLException specified index.

public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.

Downloaded by Roopa Sk
How to get the object of ResultSetMetaData:
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:

1. public ResultSetMetaData getMetaData()throws SQLException

Example :
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{ Class.forName("oracle.jdbc.driver.OracleDriver"
); Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement("select * from emp");


ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)
);

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

Downloaded by Roopa Sk
Downloaded by Roopa Sk

You might also like