Web Tech
Web Tech
HTML Introduction:
HTML, or Hyper Text Markup Language, is the standard markup language
used to create web pages. It’s a combination of Hypertext, which defines the link
between web pages, and Markup language, which is used to define the text
document within tags to structure web pages. This language is used to annotate
text so that machines can understand and manipulate it accordingly. HTML is
human-readable and uses tags to define what manipulation has to be done on the
text.
What is HTML?
HTML stands for HyperText Markup Language and it is used to create
webpages. It uses HTML tags and attributes to describe the structure and
formatting of a web page.
HTML consists of various elements, that are responsible for telling search
engines how to display page content. For example, headings, lists, images, links,
and more.
HTML Example
HTML
<!DOCTYPE html>
<html>
<head>
<title>First HTML Code</title>
</head>
<body>
<h2>Hello World</h2>
<p>Hypertext Markup Language</p>
</body>
</html>
Features of HTML
It is easy to learn and easy to use.
It is platform-independent.
Images, videos, and audio can be added to a web page.
Hypertext can be added to the text.
It is a markup language.
HTML Elements and Tags
HTML uses predefined tags and elements that instruct the browser on how
to display the content. HTML elements include an opening tag, some content, and
a closing tag. It’s important to remember to include closing tags. If omitted, the
browser applies the effect of the opening tag until the end of the page.
This section will dive into the basic structure of an HTML page, which includes
essential building-block elements like doctype declaration, HTML, head, title, and
body elements.
SGML:
SGML stands for Standard generalized markup language is a Standard
generalized markup language that makes use of a superset of extensively used
markup languages like HTML and XML. It is used for marking up files and has the
gain of now no longer depending on a particular application.
It is basically derived from GML (Generalized Markup Language), which allowed
users to work on standardized formatting styles for electronic documents. It was
developed and standardized by the International Organization for
Standards (ISO) in 1986. SGML specifies the rules for tagging elements. These tags
can then be interpreted to layout factors in specific ways.
It is used extensively to manipulate massive files which are a concern with
common revisions and want to be published in one-of-a-kind formats due to the
fact it’s far a massive and complicated system, it isn’t always but extensively used
on private computers.
Components of SGML:
SGML provides a way of describing the relationships between these entities,
elements, and attributes, and tells the computer how it can recognize the
component parts of a document and it is based on the concept of a document
being composed of a series of entities (object).
It provides rules that allow the computer to recognize where the various
elements of a text entity start and end.
Document Type Definition (DTD) in SGML is used to describe each element of
the document in a form that the computer can understand.
SGML is the simplest medium to produce files that can be read by people and
exchanged between machines and applications in a straightforward manner. It is
easy to understand by the human as well as the machine.
Features of SGML
The SGML has an entity system that provides the feature of reusability of the
content pieces.
It provides the feature for the user to create their own markup language and
document formats.
Example: In this example, we will write a code in a structured document
represented in an SGML-like format.
<EMAIL>
<RECEIVER>
<PERSON>
<FIRSTNAME>Alice</FIRSTNAME>
</PERSON>
</RECEIVER>
<BODY>
<p>This is a sample paragraph for demonstrating
SGML Example. The receiver's first name is
included in the content.</p>
</BODY>
</EMAIL>
Output:
alink color It defines the color of the active link in a document. (Not
supported in HTML5)
background URL It determines the background image for the document. (Not
supported in HTML5)
link color It determines the color of the unvisited link. (Not supported in
HTML5)
text color It determines the color of the text in the document. (Not
supported in HTML5)
vlink color It determines the color of the visited link. (Not supported in
HTML5)
<!DOCTYPE html>
<html>
<head>
<title>Body Tag</title>
</head>
<body>
<h2>Example of body tag</h2>
<p>This paragraph is written between the body tag</p>
</body>
</html>
HTML Form
An HTML form is a section of a document which contains controls such as text
fields, password fields, checkboxes, radio buttons, submit button, menus etc.
An HTML form facilitates the user to enter data that is to be sent to the server
for processing such as name, email address, password, phone number, etc. .
Tag Description
Tag Description
Output:
Output:
Checkbox Control
The checkbox control is used to check multiple options from given checkboxes.
<form>
Hobby:<br>
<input type="checkbox" id="cricket" name="cricket" value="cricket"/>
<label for="cricket">Cricket</label> <br>
<input type="checkbox" id="football" name="football" value="football"/>
<label for="football">Football</label> <br>
<input type="checkbox" id="hockey" name="hockey" value="hockey"/>
<label for="hockey">Hockey</label>
</form>
Output:
Submit button control
HTML <input type="submit"> are used to add a submit button on web page.
When user clicks on submit button, then form get submit to the server.
Syntax:
<input type="submit" value="submit">
The type = submit , specifying that it is a submit button
The value attribute can be anything which we write on button on web page.
The name attribute can be omit here.
Example:
<form>
<label for="name">Enter name</label><br>
<input type="text" id="name" name="name"><br>
<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</form>
Output:
Output:
Welcome to JavaScript
Hello JavaScript by JavaScript
Language elements
By tradition, the first example program shown for computer languages is
one called 'Hello World', which simply writes the message 'hello world' to some
type of output; it is the simplest thing that shows a program/computer is working.
Figure 1 shows the source of a simple web page which contains a JavaScript 'hello
world' program.
<html>
<head>
<title>A simple web page</title>
<script type="text/javascript">
alert("Hello world!");
</script>
</head>
<body>
Page body text
</body>
</html>
We'll consider later on the way in which this code is embedded in the web
page, and look first at the fundamentals of the language. The 'hello world' program
consists of the single line: alert("Hello world!");, all the rest of the code is the HTML
page that contains that short program.
Code layout and format
Case sensitivity:
JavaScript is a case sensitive language. Our 'hello world' program used the
function alert(); if we'd written it as 'ALERT()', or 'Alert()', the program would not
have worked, as the function would not have been recognised. Similarly, when we
come to use variables, it is important to note that 'x' and 'X' are different variables.
Whitespace
JavaScript largely ignores extra whitespace (spaces, tabs, line breaks),
which means that you can format you code with whatever pattern of spacing and
indentation that you like. Clear spacing and indentation can help to make the code
more readable and make the purpose clear. Note, however, that developers will
quite often compress entire libraries onto one line, in part to obfuscate how code
works (by its very nature, JavaScript code will usually be publicly available), and in
part to remove extra characters and shrink file sizes. This is definitely not
recommended practice, and for this course we expect all code to be clearly laid out.
Line terminators
All statements (roughly speaking, the same thing as 'a line of code') should
be ended with the semicolon character ';', as in our example above. As noted in the
introduction, JavaScript was designed to be forgiving, and one example of this is
that line terminators can be omitted; however it is considered sloppy practice to
do this, and it is possible to write ambiguous code if you rely on JavaScript to 'do
the right thing' when you leave line endings out.
Comments
All programs - whatever language they are written in – should contains
comments. Comments are messages to a human reader that explain what is going
on in the program. JavaScript recognises a number of different comment styles.
Single line comments start with '//' – anything after that will be ignored. Longer
multi-line comments can be placed between the opening characters '/*' and the
closing characters '*/'. Examples of different comment styles are shown below.
// This is a single line comment
/* This is a
multi-line
comment */
/*
* People often
* format
* multi-line comments like this
*/
radius = 5;
area = circleArea(radius);
document.write("Radius:" + radius + " Area:" + area);
The program uses a function to calculate the area of a circle. It illustrates a
number of features. We have used the variables i and j in the function. j takes the
value of 'radius' that is passed in by the main program. The function calculates the
answer as i. The variable pi was defined in the main program and thus has global
scope; it can therefore be used in the function. The variable i is defined within the
function, and has local scope; we cannot see the value of this once we return to the
main program; instead we set the variable area to the value returned by the
function. In fact, we could have used different variables called radius and area in
our function as well as in the main program.
If a function has local variables (declared using the var statement) that have
the same name as global variables, they will take precedence in the function. When
we return to the main program, we return to our original versions of the variables,
which will have retained their values, regardless of what might have happened in
the function. In contrast, if we refer to a variable without declaring it in the
function, we'll use (and possibly modify) the global variable of that name. Clearly,
it is fairly easy to make mistakes with scope, and to unintentionally over-write the
original value of global variables.
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and
method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to
get the object. But, we direct create objects.
JavaScript Array
JavaScript array is an object that represents a collection of similar type of
elements.
There are 3 ways to construct array in JavaScript
By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
<!DOCTYPE html>
<html>
<head>
<title>VBScript Introduction</title>
</head>
<body>
<!-- Paste VBScript Here -->
</body>
</html>
Step 2: Paste the below code inside the body tag of your HTML code, or you
can paste it inside the head tag. Exactly the same as you have done with
JavaScript.
javascript
Step 3: Combine both the code and run it on Microsoft Edge and you will get
the below output in the console.
html
<!DOCTYPE html>
<html>
<head>
<title>VBScript Introduction</title>
</head>
<body>
<script type="text/vbscript">
document.write("Welcome to GeeksforGeeks")
</script>
</body>
</html>
Output:
Welcome to GeeksforGeeks
VBScript Placement in HTML File
There is a flexibility given to include VBScript code anywhere in an HTML
document. But the most preferred way to include VBScript in your HTML file is as
follows −
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> and <head>...</head> sections.
Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can put VBScript in different ways −
VBScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows −
<html>
<head>
<script type = "text/Vbscript">
<!--
Function sayHello()
Msgbox("Hello World")
End Function
//-->
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
It will produce the following result − A button with the name SayHello. Upon
clicking on the Button, the message box is displayed to the user with the message
"Hello World".
VBScript Variables
A variable is a named memory location used to hold a value that can be
changed during the script execution. VBScript has only ONE fundamental data
type, Variant.
Rules for Declaring Variables −
Variable Name must begin with an alphabet.
Variable names cannot exceed 255 characters.
Variables Should NOT contain a period (.)
Variable Names should be unique in the declared context.
Declaring Variables
Variables are declared using “dim” keyword. Since there is only ONE
fundamental data type, all the declared variables are variant by default. Hence, a
user NEED NOT mention the type of data during declaration.
Example 1 − In this Example, IntValue can be used as a String, Integer or even
arrays.
Dim Var
Example 2 − Two or more declarations are separated by comma(,)
Dim Variable1,Variable2
Assigning Values to the Variables
Values are assigned similar to an algebraic expression. The variable name
on the left hand side followed by an equal to (=) symbol and then its value on the
right hand side.
Rules
The numeric values should be declared without double quotes.
The String values should be enclosed within double quotes(")
Date and Time variables should be enclosed within hash symbol(#)
Examples
' Below Example, The value 25 is assigned to the variable.
Value1 = 25
' A String Value ‘VBScript’ is assigned to the variable StrValue.
StrValue = “VBScript”
Call add()
Function add()
Var1 = 10
Var2 = 15
Dim Var3
Var3 = Var1 + Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1 ' Displays 10 as Var1 is declared at Script level
Msgbox Var2 ' Displays 15 as Var2 is declared at Script level
Msgbox Var3 ' Var3 has No Scope outside the procedure. Prints Empty
</script>
</body>
</html>
Public
Variables declared using "Public" Keyword are available to all the
procedures across all the associated scripts. When declaring a variable of type
"public", Dim keyword is replaced by "Public".
Example − In the following example, Var1 and Var2 are available at script
level while Var3 is available across the associated scripts and procedures as it is
declared as Public.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim Var1
Dim Var2
Public Var3
Call add()
Function add()
Var1 = 10
Var2 = 15
Var3 = Var1+Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1 ' Displays 10 as Var1 is declared at Script level
Msgbox Var2 ' Displays 15 as Var2 is declared at Script level
Msgbox Var3 ' Displays 25 as Var3 is declared as Public
</script>
</body>
</html>
Private
Variables that are declared as "Private" have scope only within that script in
which they are declared. When declaring a variable of type "Private", Dim keyword
is replaced by "Private".
Example − In the following example, Var1 and Var2 are available at Script
Level. Var3 is declared as Private and it is available only for this particular script.
Use of "Private" Variables is more pronounced within the Class.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim Var1
Dim Var2
Private Var3
Call add()
Function add()
Var1 = 10
Var2 = 15
Var3 = Var1+Var2
Msgbox Var3 'Displays the sum of two values.
End Function
Msgbox Var1 ' Displays 10 as Var1 is declared at Script level
Msgbox Var2 ' Displays 15 as Var2 is declared at Script level
Msgbox Var3 ' Displays 25 but Var3 is available only for this script.
</script>
</body>
</html>
VBScript - Operators
What is an operator?
Let’s take an expression 4 + 5 is equal to 9. Here, 4 and 5 are
called operands and + is called the operator. VBScript language supports following
types of operators −
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Concatenation Operators
The Arithmetic Operators
VBScript supports the following arithmetic operators −
Assume variable A holds 5 and variable B holds 10, then −
Show Examples
B ^ A will give
^ Exponentiation Operator
100000
VBScript - Procedures
What is a Function?
A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing same code over and over again. This
will enable programmers to divide a big program into a number of small and
manageable functions. Apart from inbuilt Functions, VBScript allows us to write
user-defined functions as well. This section will explain you how to write your own
functions in VBScript.
Function Definition
Before we use a function, we need to define that particular function. The
most common way to define a function in VBScript is by using the Function
keyword, followed by a unique function name and it may or may not carry a list of
parameters and a statement with an End Function keyword, which indicates the
end of the function.
The basic syntax is shown below −
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function Functionname(parameter-list)
statement 1
statement 2
statement 3
.......
statement n
End Function
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function sayHello()
msgbox("Hello there")
End Function
</script>
</body>
</html>
Calling a Function
To invoke a function somewhere later in the script, you would simple need
to write the name of that function with the Call keyword.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function sayHello()
msgbox("Hello there")
End Function
Call sayHello()
</script>
</body>
</html>
Function Parameters
Till now, we have seen function without a parameter, but there is a facility
to pass different parameters while calling a function. These passed parameters can
be captured inside the function and any manipulation can be done over those
parameters. The Functions are called using the Call Keyword.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function sayHello(name, age)
msgbox( name & " is " & age & " years old.")
End Function
Call sayHello("Tutorials point", 7)
</script>
</body>
</html>
Returning a Value from a Function
A VBScript function can have an optional return statement. This is required
if you want to return a value from a function. For example, you can pass two
numbers in a function and then you can expect from the function to return their
multiplication in your calling program.
NOTE − A function can return multiple values separated by comma as an
array assigned to the function name itself.
Example
This function takes two parameters and concatenates them and returns
result in the calling program. In VBScript, the values are returned from a function
using function name. In case if you want to return two or more values, then the
function name is returned with an array of values. In the calling program, the result
is stored in the result variable.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function concatenate(first, last)
Dim full
full = first & last
concatenate = full 'Returning the result to the function name itself
End Function
</script>
</body>
</html>
Now, we can call this function as follows −
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Function concatenate(first, last)
Dim full
full = first & last
concatenate = full 'Returning the result to the function name itself
End Function
' Here is the usage of returning value from function.
dim result
result = concatenate("Zara", "Ali")
msgbox(result)
</script>
</body>
</html>
Sub Procedures
Sub-Procedures are similar to functions but there are few differences.
Sub-procedures DONOT Return a value while functions may or may not return a
value.
Sub-procedures Can be called without call keyword.
Sub-procedures are always enclosed within Sub and End Sub statements.
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Sub sayHello()
msgbox("Hello there")
End Sub
</script>
</body>
</html>
Calling Procedures
To invoke a Procedure somewhere later in the script, you would simply need to
write the name of that procedure with or without the Call keyword.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Sub sayHello()
msgbox("Hello there")
End Sub
sayHello()
</script>
</body>
</html>
Conditional Statements
Conditional statements are used to perform different actions for different
decisions.
In VBScript we have four conditional statements:
If statement - executes a set of code when a condition is true
If...Then...Else statement - select one of two sets of lines to execute
If...Then...ElseIf statement - select one of many sets of lines to execute
Select Case statement - select one of many sets of lines to execute
VBScript If Statement
An If statement consists of a Boolean expression followed by one or more
statements. If the condition is said to be True, the statements under If condition(s)
are Executed. If the Condition is said to be False, the statements after the If loop are
executed.
Syntax
The syntax of an If statement in VBScript is −
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
End If
Flow Diagram
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 20
Dim b : b = 10
If a > b Then
Document.write "a is Greater than b"
End If
</script>
</body>
</html>
When the above code is executed, it produces the following result −
a is Greater than b
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 5
Dim b : b = 25
If a > b Then
Document.write "a is Greater"
Else
Document.write "b is Greater"
End If
</script>
</body>
</html>
When the above code is executed, it produces the following result −
b is Greater
case 2
Document.write "The Number is the only Even Prime Number"
case 3
Document.write "The Number is the Least Odd Prime Number"
case else
Document.write "Unknown Number"
End select
</script>
</body>
</html>
In the above example, the value of MyVar is 1. Hence, Case 1 would be executed.
The Number is the Least Composite Number
Looping Constructs:
There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow more
complicated execution paths. A loop statement allows us to execute a statement or
group of statements multiple times and following is the general from of a loop
statement in VBScript.
VBScript For Loops
A for loop is a repetition control structure that allows a developer to
efficiently write a loop that needs to execute a specific number of times.
Syntax
The syntax of a for loop in VBScript is −
For counter = start To end [Step stepcount]
[statement 1]
[statement 2]
....
[statement n]
[Exit For]
[statement 11]
[statement 22]
....
[statement n]
Next
Flow Diagram
Here is the flow of control in a For Loop −
The For step is executed first. This step allows you to initialize any loop
control variables and increment the step counter variable.
Secondly, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control
jumps to the next statement just after the For Loop.
After the body of the for loop executes, the flow of control jumps to
the Next statement. This statement allows you to update any loop control variables.
It is updated based on the step counter value.
The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the For Loop terminates.
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 10
For i = 0 to a Step 2 'i is the counter variable and it is incremented by 2
document.write("The value is i is : " & i)
document.write("<br></br>")
Next
</script>
</body>
</html>
When the above code is compiled and executed, it produces the following result −
The value is i is : 0
The value is i is : 2
The value is i is : 4
The value is i is : 6
The value is i is : 8
The value is i is : 10
msgbox fruitnames
</script>
</body>
</html>
When the above code is executed, it prints all the fruitnames with one item in each
line.
apple
orange
cherries
Example
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim Counter : Counter = 10
While Counter < 15 ' Test value of Counter.
Counter = Counter + 1 ' Increment Counter.
document.write("The Current Value of the Counter is : " & Counter)
document.write("<br></br>")
Wend ' While loop exits if Counter Value becomes 15.
</script>
</body>
</html>
When the above code is executed, it prints the following output in the console.
The Current Value of the Counter is : 11
The Current Value of the Counter is : 12
Loop
Flow Diagram
Example
The below example uses Do..while loop to check the condition at the
beginning of the loop. The statements inside the loop are executed only if the
condition becomes True.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Do While i < 5
i=i+1
Document.write("The value of i is : " & i)
Document.write("<br></br>")
Loop
</script>
</body>
</html>
When the above code is executed, it prints the following output on the console.
The value of i is : 1
The value of i is : 2
The value of i is : 3
The value of i is : 4
The value of i is : 5
Example
The below example uses Exit For. If the value of the Counter reaches 4, the
For Loop is Exited and control jumps to the next statement immediately after the
For Loop.
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
Dim a : a = 10
For i = 0 to a Step 2 'i is the counter variable and it is incremented by 2
document.write("The value is i is : " & i)
document.write("<br></br>")
If i = 4 Then
i = i*10 'This is executed only if i = 4
document.write("The value is i is : " & i)
Exit For 'Exited when i = 4
End If
Next
</script>
</body>
</html>
When the above code is executed, it prints the following output in the console.
The value is i is : 0
The value is i is : 2
The value is i is : 4
The value is i is : 40
</script>
</body>
</html>
When the above code is executed, it prints the following output in the console.
The Value of i is : 0
The Value of i is : 2
The Value of i is : 4
The Value of i is : 6
The Value of i is : 8
The Value of i is : 10
What is an Object
VBScript runtime objects help us to accomplish various tasks. This section
will help you understand how to instantiate an object and work with it.
Syntax
In order to work with objects seamlessly, we need to declare the object and
instantiate it using Set Keyword.
Dim objectname 'Declare the object name
Set objectname = CreateObject(object_type)
Example
In the below example, we are creating an object of type Scripting.Dictionary.
Dim obj
Set obj = CreateObject("Scripting.Dictionary")
Cookies:
What are Cookies?
Web Browsers and Servers use HTTP protocol to communicate and HTTP is
a stateless protocol. But for a commercial website, it is required to maintain
session information among different pages. For example, one user registration
ends after completing many pages. But how to maintain user's session information
across all the web pages. In many situations, using cookies is the most efficient
method of remembering and tracking preferences, purchases, commissions and
other information required for better visitor experience or site statistics.
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie.
The browser may accept the cookie. If it does, it is stored as a plain text record on
the visitor's hard drive. Now, when the visitor arrives at another page on your site,
the browser sends the same cookie to the server for retrieval. Once retrieved, your
server knows/remembers what was stored earlier. Cookies are a plain text data
record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire
when the visitor quits the browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that set the cookie. This may be blank
if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key and value pairs.
Cookies were originally designed for CGI programming and cookies' data is
automatically transmitted between the web browser and web server, so CGI scripts
on the server can read and write cookie values that are stored on the client.
VBScript can also manipulate cookies using the cookie property of
the Document object. VBScript can read, create, modify and delete the cookie or
cookies that apply to the current web page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to
the document.cookie object, which looks like this −
Syntax
document.cookie = "key1 = value1;key2 = value2;expires = date"
Here expires attribute is optional. If you provide this attribute with a valid
date or time, then cookie will expire at the given date or time and after that cookies'
value will not be accessible.
Example
Following is the example to set a customer name in input cookie.
<html>
<head>
<script type = "text/vbscript">
Function WriteCookie
If document.myform.customer.value = "" Then
msgbox "Enter some value!"
Else
cookievalue = (document.myform.customer.value)
document.cookie = "name = " + cookievalue
msgbox "Setting Cookies : " & "name = " & cookievalue
End If
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
It will produce the following result. Now enter something in the textbox and press
the button "Set Cookie" to set the cookies.
Top of Form
Enter name:
Bottom of Form
Now, your system has a cookie called name. You can set multiple cookies using
multiple key = value pairs separated by comma. You will learn how to read this
cookie in next section.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of
the document.cookie object is the cookie. So, you can use this string whenever you
want to access the cookie. The document.cookie string will keep a list of name =
value pairs separated by semicolons where name is the name of a cookie and value
is its string value. You can use strings' split() function to break the string into key
and values as follows −
Example
Following is the example to get the cookies set in the previous section −
<html>
<head>
<script type = "text/vbscript">
Function ReadCookie
allcookies = document.cookie
msgbox "All Cookies : " + allcookies
cookiearray = split(allcookies,";")
For i = 0 to ubound(cookiearray)
Name = Split(cookiearray(i),"=")
Msgbox "Key is : " + Name(0) + " and Value is : " + Name(1)
Next
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>
Note − Here, UBound is a method of Array class, which returns the length of
an array. We will discuss Arrays in a separate chapter; until that time, please try to
digest it.
It will produce the following result. Now, press the button "Get Cookie" to
see the cookies, which you have set in previous section.
Top of Form
Bottom of Form
Note − There may be some other cookies already set on your machine. So, above
code will show you all the cookies set at your machine.
Setting the Cookies Expiration Date
You can extend the life of a cookie beyond the current browser session by setting
an expiration date and saving the expiration date within the cookie. This can be
done by setting the expires attribute to a date and time.
Example
The following example illustrates how to set cookie expiration date after 1 Month
−
<html>
<head>
<script type = "text/vbscript">
Function WriteCookie()
x = now()
y = dateadd("m",1,now()) ' Making it to expire next
cookievalue = document.myform.customer.value
document.cookie = "name = " & cookievalue
document.cookie = "expires = " & y
msgbox("Setting Cookies : " & "name=" & cookievalue )
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
Deleting a Cookie
Sometimes, you will want to delete a cookie so that subsequent attempts to
read the cookie return nothing. To do this, you just need to set the expiration date
to a time in the past.
Example
The following example illustrates how to delete a cookie by setting its expiration
date 1 Month in the past −
<html>
<head>
<script type = "text/vbscript">
Function WriteCookie()
x = now()
x = now()
a = Month(x)-1
b = day(x)
c = year(x)
d = DateSerial(c,a,b)
e = hour(x)
msgbox e
f = minute(x)
msgbox f
d = cdate(d & " " & e & ":" & f)
msgbox d
cookievalue = document.myform.customer.value
document.cookie = "name = " & cookievalue
document.cookie = "expires = " & d
msgbox("Setting Cookies : " & "name=" & cookievalue )
End Function
</script>
</head>
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
UNIT - IV
DHTML Introduction
DHTML, or Dynamic HTML, is a technology that differs from traditional
HTML. DHTML combines HTML, CSS, JavaScript, and the Document Object Model
(DOM) to create dynamic content. It uses the Dynamic Object Model to modify
settings, properties, and methods. Scripting is also an essential component of
DHTML, which was part of earlier computing trends. It is supported by some
versions of Netscape Navigator and Internet Explorer 4.0 and higher.
HTML: HTML stands for Hypertext Markup Language and it is a client-side markup
language. It is used to build the block of web pages.
Javascript: It is a Client-side Scripting language. Javascript is supported by most of
browsers, and also has cookie collection to determine the user’s needs.
CSS: The abbreviation of CSS is Cascading Style Sheet. It helps in the styling of the
web pages and helps in designing of the pages. The CSS rules for DHTML will be
modified at different levels using JS with event handlers which adds a significant
amount of dynamism with very little code.
DOM: It is known as a Document Object Model which acts as the weakest link in it.
The only defect in it is that most of the browsers does not support DOM. It is a way
to manipulate the static content.
DHTML is not a technology; rather, it is the combination of three different
technologies, client-side scripting (JavaScript or VBScript), cascading style sheets
and document object model.
Note: Many times DHTML is confused with being a language like HTML but it is not.
It must be kept in mind that it is an interface or browsers enhancement feature
which makes it possible to access the object model through Javascript language and
hence make the webpage more interactive.
Key Features:
Tags and their properties can be changed using DHTML.
It is used for real-time positioning.
Dynamic fonts can be generated using DHTML.
It is also used for data binding.
It makes a webpage dynamic and be used to create animations, games,
applications along with providing new ways of navigating through websites.
The functionality of a webpage is enhanced due to the usage of low-
bandwidth effect by DHTML.
DHTML also facilitates the use of methods, events, properties, and codes.
Why Use DHTML?
DHTML makes a webpage dynamic but Javascript also does, the question
arises that what different does DHTML do? So the answer is that DHTML has the
ability to change a webpages look, content and style once the document has loaded
on our demand without changing or deleting everything already existing on the
browser’s webpage. DHTML can change the content of a webpage on demand
without the browser having to erase everything else, i.e. being able to alter changes
on a webpage even after the document has completely loaded.
Advantages:
Size of the files are compact in compared to other interactional media like
Flash or Shockwave, and it downloads faster.
It is supported by big browser manufacturers like Microsoft and Netscape.
Highly flexible and easy to make changes.
Viewer requires no extra plug-ins for browsing through the webpage that
uses DHTML, they do not need any extra requirements or special software to view
it.
User time is saved by sending less number of requests to the server. As it is
possible to modify and replace elements even after a page is loaded, it is not
required to create separate pages for changing styles which in turn saves time in
building pages and also reduces the number of requests that are sent to the server.
It has more advanced functionality than a static HTML. it is capable of
holding more content on the web page at the same time.
Disadvantages:
It is not supported by all the browsers. It is supported only by recent
browsers such as Netscape 6, IE 5.5, and Opera 5 like browsers.
Learning of DHTML requires a lot of pre-requisites languages such as HTML,
CSS, JS, etc should be known to the designer before starting with DHTML which is a
long and time-consuming in itself.
Implementation of different browsers are different. So if it worked in one
browser, it might not necessarily work the same way in another browser.
Even after being great with functionality, DHTML requires a few tools and
utilities that are some expensive. For example, the DHTML text editor,
Dreamweaver. Along with it the improvement cost of transferring from HTML to
DHTML makes cost rise much higher.
Difference between HTML and DHTML:
HTML is a markup language while DHTML is a collection of technologies.
HTML is used to create static webpages while DHTML is capable of creating
dynamic webpages.
DHTML is used to create animations and dynamic menus but HTML not used.
HTML sites are slow upon client-side technologies whereas DHTML sites are
comparatively faster.
Web pages created using HTML are rather simple and have no styling as it uses only
one language whereas DHTML uses HTML, CSS, and Javascript which results in a
much better and way more presentable webpage.
HTML cannot be used as server side code but DHTML used as server side code.
DHTML needs database connectivity but not in case of HTML.
Files in HTML are stored using .htm or .html extension while DHTML uses .dhtm
extension.
HTML requires no processing from the browser but DHTML does.
What is CSS?
CSS, or Cascading Style Sheets, is a language used to style and enhance websites.
It controls how HTML elements—such as text, images, and buttons—are displayed
on a webpage. With CSS, you can adjust font sizes and colors, add backgrounds,
and manage the layout, transforming a basic webpage into a visually appealing
and user-friendly experience. CSS also simplifies layout management across
multiple web pages by using external stylesheets stored in CSS files.
Different Ways to Use CSS
CSS has three ways to style the HTML:
Inline: Add styles directly to HTML elements using the style attribute (limited
use).
Internal: Place styles within a <style> tag inside the HTML file, usually within
the <head> section
External: Create a separate CSS file with a .css extension and link it to your HTML
file using the <link> tag.
Types of CSS
CSS (Cascading Style Sheet) describes the HTML elements which are
displayed on screen, paper, or in other media. It saves a lot of time. It controls the
layout of multiple web pages at one time. It sets the font-size, font-family, color,
background color on the page.
It allows us to add effects or animations to the website. We use CSS to
display animations like buttons, effects, loaders or spinners, and also animated
backgrounds.
Without using CSS, the website will not look attractive. There are 3 types
of CSS which are below:
Inline CSS
Internal/ Embedded CSS
External CSS
1. Internal CSS
The Internal CSS has <style> tag in the <head> section of
the HTML document. This CSS style is an effective way to style single pages. Using
the CSS style for multiple web pages is time-consuming because we require placing
the style on each web page.
We can use the internal CSS by using the following steps:
1. Firstly, open the HTML page and locate the <head>
2. Put the following code after the <head>
<style type="text/css">
3. Add the rules of CSS in the new line.
Example:
body {
background-color: black;
}
h1 {
color: white;
padding: 50px;
}
4. Close the style tag.
</style>
After adding the internal CSS, the complete HTML file looks like the following:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: black;
}
h1 {
color: red;
padding: 50px;
}
</style>
</head>
<body>
<h2>CSS types</h2>
<p>Cascading Style sheet types: inline, external and internal</p>
</body>
</html>
We can also use the selectors (class and ID) in the style sheet.
Example:
.class {
property1 : value1;
property2 : value2;
property3 : value3;
}
#id {
property1 : value1;
property2 : value2;
property3 : value3;
}
Pros of Internal CSS
Internal CSS cannot upload multiple files when we add the code with the HTML
page.
Cons of Internal CSS:
Adding code in the HTML document will reduce the page size and loading time of
the webpage.
2. External CSS
In external CSS, we link the web pages to the external .css file. It is created
by text editor. The CSS is more efficient method for styling a website. By editing
the .css file, we can change the whole site at once.
To use the external CSS, follow the steps, given below:
1. Create a new .css file with text editor, and add Cascading Style Sheet rules too.
For example:
.xleftcol {
float: right;
width: 35%;
background:#608800;
}
.xmiddlecol {
float: right;
width: 35%;
background:#eff3df;
}
2. Add a reference to the external .cssfile right after <title> tag in
the <head> section of HTML sheet:
<link rel="stylesheet" type="text/css" href="style.css" />
Pros of External CSS:
Our files have a cleaner structure and smaller in size.
We use the same .css file for multiple web pages in external CSS.
Cons of External CSS:
The pages cannot be delivered correctly before the external CSS is loaded.
In External CSS, uploading many CSS files can increase the download time of a
website.
3. Inline CSS
Inline CSS is used to style a specific HTML element. Add a style attribute to
each HTML tag without using the selectors. Managing a website may difficult if we
use only inline CSS. However, Inline CSS in HTML is useful in some situations. We
have not access the CSS files or to apply styles to element.
In the following example, we have used the inline CSS in <p> and <h1> tag.
<!DOCTYPE html>
<html>
<body style="background-color:white;">
<h1 style="color:Red;padding:20px;">CSS Tutorials</h1>
<p style="color:blue;">It will be useful here.</p>
</body>
</html>
Pros of inline CSS:
We can create CSS rules on the HTML page.
We cannot create and upload a separate document in inline CSS.
Cons of inline CSS:
Inline CSS, adding CSS rules to HTML elements is time-
consuming and messes up the HTML structure.
It styles multiple elements at the same time which can affect the page size
and download time of the page.
HTML DOM (Document Object Model) is a hierarchical representation of
HTML documents. It defines the structure and properties of elements on a
webpage, enabling JavaScript to dynamically access, manipulate, and update
content, enhancing interactivity and functionality.
Note: It is called a Logical structure because DOM doesn’t specify any
relationship between objects.
What is DOM?
DOM, or Document Object Model, is a programming interface that
represents structured documents like HTML and XML as a tree of objects. It
defines how to access, manipulate, and modify document elements using
scripting languages like JavaScript.
So basically Document Object Model is an API that represents and interacts
with HTML or XML documents.
The DOM is a W3C (World Wide Web Consortium) standard and it defines
a standard for accessing documents.
The W3C Dom standard is divided into three different parts:
Core DOM – standard model for all document types
XML DOM – standard model for XML documents
HTML DOM – standard model for HTML documents
HTML DOM
HTML DOM is a standard object model and programming interface
for HTML documents. HTML DOM is a way to represent the webpage in
a structured hierarchical way so that it will become easier for programmers and
users to glide through the document.
With HTML DOM, we can easily access and manipulate tags, IDs, classes,
attributes, or elements of HTML using commands or methods provided by the
document object.
Using DOM JavaScript we get access to HTML as well as CSS of the web page
and can also modify the behavior of the HTML elements.
Why is DOM Required?
HTML is used to structure the web pages and Javascript is used to
add behavior to our web pages. When an HTML file is loaded into the browser, the
JavaScript can not understand the HTML document directly. So it interprets and
interacts with the Document Object Model (DOM), which is created by the
browser based on the HTML document.
DOM is basically the representation of the same HTML document but in a
tree-like structure composed of objects. JavaScript can not understand the
tags(<h1>H</h1>) in HTML document but can understand object h1 in DOM.
JavaScript interprets DOM easily, using it as a bridge to access and
manipulate the elements. DOM Javascript allow access to each of the objects (h1,
p, etc) by using different functions.
The Document Object Model (DOM) is essential in web development for several
reasons:
Dynamic Web Pages: It allows you to create dynamic web pages. It enables
the JavaScript to access and manipulate page content, structure, and style
dynamically which gives interactive and responsive web experiences, such as
updating content without reloading the entire page or responding to user actions
instantly.
Interactivity: With the DOM, you can respond to user actions (like clicks, inputs,
or scrolls) and modify the web page accordingly.
Content Updates: When you want to update the content without refreshing the
entire page, the DOM enables targeted changes making the web applications more
efficient and user-friendly.
Cross-Browser Compatibility: Different browsers may render HTML and CSS in
different ways. The DOM provides a standardized way to interact with page
elements.
Single-Page Applications (SPAs): Applications built with frameworks such as
React or Angular, heavily rely on the DOM for efficient rendering and updating of
content within a single HTML page without reloading the full page.
Structure of DOM
DOM can be thought of as a Tree or Forest (more than one tree). The
term structure model is sometimes used to describe the tree-like representation
of a document.
Each branch of the tree ends in a node, and each node contains
objects Event listeners can be added to nodes and triggered on an occurrence of
a given event. One important property of DOM structure models is structural
isomorphism: if any two DOM implementations are used to create a
representation of the same document, they will create the same structure model,
with precisely the same objects and relationships.
Why DOM is called an Object Model?
Documents are modeled using objects, and the model includes not only the
structure of a document but also the behavior of a document and the objects of
which it is composed like tag elements with attributes in HTML.
Properties of DOM
Let’s see the properties of the document object that can be accessed and modified
by the document object.
Representation of the DOM
Window Object: Window Object is object of the browser which is always at top of
the hierarchy. It is like an API that is used to set and access all the properties and
methods of the browser. It is automatically created by the browser.
Document object: When an HTML document is loaded into a window, it
becomes a document object. The ‘document’ object has various properties that
refer to other objects which allow access to and modification of the content of the
web page. If there is a need to access any element in an HTML page, we always
start with accessing the ‘document’ object. Document object is property of
window object.
Form Object: It is represented by form tags.
Link Object: It is represented by link tags.
Anchor Object: It is represented by a href tags.
Form Control Elements: Form can have many control elements such as text fields,
buttons, radio buttons, checkboxes, etc.
Methods of Document Object
DOM provides various methods that allows users to interact with and manipulate
the document. Some commonly used DOM methods are:
Method Description
Example: In this example, We use HTML element id to find the DOM HTML
element.
HTML
<!DOCTYPE html>
<html>
<body>
<h2>GeeksforGeeks</h2>
<!-- Finding the HTML Elements by their Id in DOM -->
<p id="intro">
A Computer Science portal for geeks.
</p>
<p>
This example illustrates the <b>getElementById</b> method.
</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"GeeksforGeeks introduction is: " + element.innerHTML;
</script>
</body>
</html>
Output:
Example : This example describes the representation of the HTML elements in the
tree structure.
html
<table>
<ROWS>
<tr>
<td>Car</td>
<td>Scooter</td>
</tr>
<tr>
<td>MotorBike</td>
<td>Bus</td>
</tr>
</ROWS>
</table>
DHTML DOM
DHTML DOM stands for Dynamic HTML Document Object Model.
It is a w3c standard, which is a standard interface of programming for HTML.
It is mainly used for defining the objects and properties of all elements in HTML. It
also defines the methods for accessing the HTML elements.
Example: The following program helps in understanding the concept of DHTML
DOM. This example changes the color of text and displays the text in red colour
automatically.
<html>
<head>
<title>
Example of DHTML DOM
</title>
</head>
<body>
<font color = "blue">
<p id="demo"> This text changes color when the page loaded. </p>
</font>
<script type="text/javascript">
document.getElementById('demo').style.color = "red";
</script>
</body>
</html>
Output:
DHTML Events
An event is defined as changing the occurrence of an object.
It is compulsory to add the events in the DHTML page. Without events, there will be
no dynamic content on the HTML page. The event is a term in the HTML, which
triggers the actions in the web browsers.
Suppose, any user clicks an HTML element, then the JavaScript code associated
with that element is executed. Actually, the event handlers catch the events
performed by the user and then execute the code.
Example of events:
Click a button.
Submitting a form.
An image loading or a web page loading, etc.
Following table describes the Event Handlers used in the DHTML:
1. onabort It occurs when the user aborts the page or media file loading.
11. onmousedown It occurs when a user presses the button of a mouse over an
HTML element.
12. onmousemove It occurs when a user moves the cursor on an HTML object.
13. onmouseover It occurs when a user moves the cursor over an HTML object.
14. onmouseout It occurs or triggers when the mouse pointer is moved out of
an HTML element.
15. onmouseup It occurs or triggers when the mouse button is released over
an HTML element.
17. onselect It occurs after selecting the content or text on a web page.
18. onsubmit It is triggered when the user clicks a button after the
submission of a form.
Following are the different examples using the different event handlers,
which helps us to understand the concept of DHTML events:
Example 1: This example uses the onclick event handler, which is used to
change the text after clicking.
<html>
<head>
<title>
Example of onclick event
</title>
<script type="text/javascript">
function ChangeText(ctext)
{
ctext.innerHTML=" Hi JavaTpoint! ";
}
</script>
</head>
<body>
<font color="red"> Click on the Given text for changing it: <br>
</font>
<font color="blue">
<h1 onclick="ChangeText(this)"> Hello World! </h1>
</font>
</body>
</html>
Output:
Example 2: This example uses the onsubmit event handler, which gives an
alert after clicking on a submit button.
<html>
<head>
<title>
Example of onsubmit event
</title>
</head>
<body>
<form onsubmit="Submit_Form()">
<label> Enter your name: </label>
<input type="text">
<label> Enter your Roll no: </label>
<input type="Number">
<input type="submit" value="submit">
</form>
<script type="text/javascript">
function Submit_Form()
{
alert(" Your form is submitted");
}
</script>
</body>
</html>
Output:
UNIT - V:
Extensible Mark-Up Language (XML): Introduction
What is xml
Xml (eXtensible Markup Language) is a mark up language.
XML is designed to store and transport data.
Xml was released in late 90’s. it was created to provide an easy to use and store self
describing data.
XML became a W3C Recommendation on February 10, 1998.
XML is not a replacement for HTML.
XML is designed to be self-descriptive.
XML is designed to carry data, not to display data.
XML tags are not predefined. You must define your own tags.
XML is platform independent and language independent.
Why xml
Platform Independent and Language Independent: The main benefit of xml
is that you can use it to take data from a program like Microsoft SQL, convert it into
XML then share that XML with other programs and platforms. You can
communicate between two platforms which are generally very difficult.
The main thing which makes XML truly powerful is its international acceptance.
Many corporation use XML interfaces for databases, programming, office
application mobile phones and more. It is due to its platform independent feature.
What is the difference between XML and HTML?
XML HTML
XML stands for Extensible Markup HTML stands for a hypertext markup
Language. language.
The main purpose of XML is used to The main purpose of HTML is used to
transfer the data. create and design the webpage.
It does not allow any error in the coding. If there is a small error in the code, then
it is ignored by the HTML.
In XML, we have to perform the nesting The nesting of code does not affect the
operation appropriately. HTML code.
In XML, the closing tag is mandatory. But in HTML, some tags do not have the
closing tag.
XML requires the code around XML Here no quote requires the value of the
attribute values. attribute.
The convention should express all the The HTML natively offers Object
objects in XML. Most of the objects use support.
elements and attributes.
XML supports the namespace. With the The concept of namespace does not
help of a namespace, we can remove the supported by HTML. In HTML, we can
collision risk created when we combine avoid the naming collision by
it with another document. implementing prefixes in the object or
performing nesting operations.
In XML, there is a requirement for the In HTML, we can provide direct mapping
connection between the MAP for the application data.
application type to the element and
attribute of the XML.
In XML, we use the document, which is In HTML, we only use formatted text.
very lengthy in size.
In XML, all the tags are enclosed by the In HTML, all the tags are enclosed by the
closing square bracket. angle bracket.
XML is neither a programming language With the help of HTML, we can maintain
nor a presentation language. the data presentation on the webpage.
XML supports some data types. The HTML supports no concept of datatype.
supported data types are Boolean,
integer, duration, date, etc.
XML - Syntax
we will discuss the simple syntax rules to write an XML document. Following is a
complete XML document −
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
You can notice there are two kinds of information in the above example −
Markup, like <contact-info>
The text, or the character data, Tutorials Point and (040) 123-4567.
The following diagram depicts the syntax rules to write different types of markup
and text in an XML document.
Let us see each component of the above diagram in detail.
XML Declaration
The XML document can optionally have an XML declaration. It is written as follows
−
<?xml version = "1.0" encoding = "UTF-8"?>
Where version is the XML version and encoding specifies the character encoding
used in the document.
Syntax Rules for XML Declaration
The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is
written in lower-case.
If document contains XML declaration, then it strictly needs to be the first
statement of the XML document.
The XML declaration strictly needs be the first statement in the XML document.
An HTTP protocol can override the value of encoding that you put in the XML
declaration.
XML Attributes
XML elements can have attributes. By the use of attributes we can add the
information about the element.
XML attributes enhance the properties of the elements.
Note: XML attributes must always be quoted. We can use single or double quote.
Let us take an example of a book publisher. Here, book is the element and publisher
is the attribute.
<book publisher="Tata McGraw Hill"></book>
Or
<book publisher='Tata McGraw Hill'></book>
Metadata should be stored as attribute and data should be stored as element.
<book>
<book category="computer">
<author> A & B </author>
</book>
Data can be stored in attributes or in child elements. But there are some limitations
in using attributes, over child elements.
XML DTD
What is DTD
DTD stands for Document Type Definition. It defines the legal building
blocks of an XML document. It is used to define document structure with a list of
legal elements and attributes.
Purpose of DTD
Its main purpose is to define the structure of an XML document. It contains
a list of legal elements and define the structure with the help of them.
Checking Validation
Before proceeding with XML DTD, you must check the validation. An XML
document is called "well-formed" if it contains the correct syntax.
A well-formed and valid XML document is one which have been validated
against DTD.
Visit http://www.xmlvalidation.com to validate the XML file.
Description of DTD
<!DOCTYPE employee : It defines that the root element of the document is
employee.
<!ELEMENT employee: It defines that the employee element contains 3 elements
"firstname, lastname and email".
<!ELEMENT firstname: It defines that the firstname element is #PCDATA typed.
(parse-able data type).
<!ELEMENT lastname: It defines that the lastname element is #PCDATA typed.
(parse-able data type).
<!ELEMENT email: It defines that the email element is #PCDATA typed. (parse-able
data type).
XML DTD with entity declaration
A doctype declaration can also define special strings that can be used in the XML
file.
An entity has three parts:
An ampersand (&)
An entity name
A semicolon (;)
Syntax to declare entity:
<!ENTITY entity-name "entity-value">
Let's see a code to define the ENTITY in doctype declaration.
author.xml
<?xml version="1.0" standalone="yes" ?>
<!DOCTYPE author [
<!ELEMENT author (#PCDATA)>
<!ENTITY sj "Sonoo Jaiswal">
]>
<author>&sj;</author>
In the above example, sj is an entity that is used inside the author element. In such
case, it will print the value of sj entity that is "Sonoo Jaiswal".
DTD - XML Building Blocks
The main building blocks of both XML and HTML documents are elements.
Elements
Elements are the main building blocks of both XML and HTML documents.
Examples of HTML elements are "body" and "table". Examples of XML elements
could be "note" and "message". Elements can contain text, other elements, or be
empty. Examples of empty HTML elements are "hr", "br" and "img".
Examples:
<body>some text</body>
<message>some text</message>
Attributes
Attributes provide extra information about elements.
Attributes are always placed inside the opening tag of an element. Attributes
always come in name/value pairs. The following "img" element has additional
information about a source file:
<img src="computer.gif" />
The name of the element is "img". The name of the attribute is "src". The value of
the attribute is "computer.gif". Since the element itself is empty it is closed by a "
/".
Entities
Some characters have a special meaning in XML, like the less than sign (<) that
defines the start of an XML tag.
Most of you know the HTML entity: " ". This "no-breaking-space" entity is
used in HTML to insert an extra space in a document. Entities are expanded when
a document is parsed by an XML parser.
The following entities are predefined in XML:
< <
> >
& &
" "
' '
PCDATA
PCDATA means parsed character data.
Think of character data as the text found between the start tag and the end tag of
an XML element.
PCDATA is text that WILL be parsed by a parser. The text will be examined by the
parser for entities and markup.
Tags inside the text will be treated as markup and entities will be expanded.
However, parsed character data should not contain any &, <, or > characters; these
need to be represented by the & < and > entities, respectively.
CDATA
CDATA means character data.
CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT be
treated as markup and entities will not be expanded.
DTD - Elements
Declaring Elements
In a DTD, XML elements are declared with the following syntax:
<!ELEMENT element-name category>
or
<!ELEMENT element-name (element-content)>
Empty Elements
Empty elements are declared with the category keyword EMPTY:
<!ELEMENT element-name EMPTY>
Example:
<!ELEMENT br EMPTY>
XML example:
<br />
Example:
ADVERTISEMENT
Example:
<address>
<name id = "123">Tanmay Patil</name>
</address>
Let us go through the above code −
Begin with the XML declaration with the following statement −
<?xml version = "1.0"?>
Immediately following the XML header is the document type declaration,
commonly referred to as the DOCTYPE as shown below −
The DOCTYPE informs the parser that a DTD is associated with this XML document.
The DOCTYPE declaration has an exclamation mark (!) at the start of the element
name.
<!DOCTYPE address [
Following is the body of DTD. Here we have declared element and attribute −
<!ELEMENT address ( name )>
<!ELEMENT name ( #PCDATA )>
Attribute id for the element name is defined as given below −
Here attribute type is CDATA and its value is #REQUIRED.
<!ATTLIST name id CDATA #REQUIRED>
Rules of Attribute Declaration
All attributes used in an XML document must be declared in the Document Type
Definition (DTD) using an Attribute-List Declaration
Attributes may only appear in start or empty tags.
The keyword ATTLIST must be in upper case
No duplicate attribute names will be allowed within the attribute list for a given
element.
Attribute Types
When declaring attributes, you can specify how the processor should handle the
data that appears in the value. We can categorize attribute types in three main
categories −
String type
Tokenized types
Enumerated types
Following table provides a summary of the different attribute types −
CDATA
1 CDATA is character data (text and not markup). It is a String Attribute
Type.
ID
2 It is a unique identifier of the attribute. It should not appear more
than once. It is a Tokenized Attribute Type.
IDREF
3 It is used to reference an ID of another element. It is used to establish
connections between elements. It is a Tokenized Attribute Type.
IDREFS
4
It is used to reference multiple ID's. It is a Tokenized Attribute Type.
ENTITY
5 It represents an external entity in the document. It is a Tokenized
Attribute Type.
ENTITIES
6 It represents a list of external entities in the document. It is
a Tokenized Attribute Type.
NMTOKEN
7 It is similar to CDATA and the attribute value consists of a valid XML
name. It is a Tokenized Attribute Type.
NMTOKENS
8 It is similar to CDATA and the attribute value consists a list of valid
XML name. It is a Tokenized Attribute Type.
9 NOTATION
An element will be referenced to a notation declared in the DTD
document. It is an Enumerated Attribute Type.
Enumeration
10 It allows defining a specific list of values where one of the values must
match. It is an Enumerated Attribute Type.
<!DOCTYPE address [
<!ELEMENT address ( name )>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA "0">
]>
<address>
<name id = "123">
Tanmay Patil
</name>
</address>
In this example we have name element with attribute id whose default value is 0.
The default value is been enclosed within the double quotes.
FIXED Values
#FIXED keyword followed by the fixed value is used when you want to specify that
the attribute value is constant and cannot be changed. A common use of fixed
attributes is specifying version numbers.
Syntax
Following is the syntax of fixed values −
<!ATTLIST element-name attribute-name attribute-type #FIXED "value" >
where #FIXED is an attribute value defined.
Example
Following is a simple example of attribute declaration with FIXED value −
<?xml version = "1.0"?>
<!DOCTYPE address [
<!ELEMENT address (company)*>
<!ELEMENT company (#PCDATA)>
<!ATTLIST company name NMTOKEN #FIXED "tutorialspoint">
]>
<address>
<company name = "tutorialspoint">we are a free online teaching
faculty</company>
</address>
In this example we have used the keyword #FIXED where it indicates that the value
"tutorialspoint" is the only value for the attribute name of element <company>. If
we try to change the attribute value then it gives an error.
Following is an invalid DTD −
<?xml version = "1.0"?>
<!DOCTYPE address [
<!ELEMENT address (company)*>
<!ELEMENT company (#PCDATA)>
<!ATTLIST company name NMTOKEN #FIXED "tutorialspoint">
]>
<address>
<company name = "abc">we are a free online teaching faculty</company>
</address>
REQUIRED values
Whenever you want specify that an attribute is required, use #REQUIRED keyword.
Syntax
Following is the syntax of #REQUIRED −
<!ATTLIST element-name attribute-name attribute-type #REQUIRED>
where #REQUIRED is an attribute type defined.
Example
Following is a simple example of DTD attribute declaration with #REQUIRED
keyword −
<?xml version = "1.0"?>
<!DOCTYPE address [
<!ELEMENT address ( name )>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA #REQUIRED>
]>
<address>
<name id = "123">
Tanmay Patil
</name>
</address>
In this example we have used #REQUIRED keyword to specify that the
attribute id must be provided for the element-name name
IMPLIED Values
When declaring attributes you must always specify a value declaration. If the
attribute you are declaring has no default value, has no fixed value, and is not
required, then you must declare that the attribute as implied. Keyword #IMPLIED
is used to specify an attribute as implied.
Syntax
Following is the syntax of #IMPLIED −
<!ATTLIST element-name attribute-name attribute-type #IMPLIED>
where #IMPLIED is an attribute type defined.
Example
Following is a simple example of #IMPLIED
<?xml version = "1.0"?>
<!DOCTYPE address [
<!ELEMENT address ( name )>
<!ELEMENT name ( #PCDATA )>
<!ATTLIST name id CDATA #IMPLIED>
]>
<address>
<name />
</address>
In this example we have used the keyword #IMPLIED as we do not want to specify
any attributes to be included in element name. It is optional.
DTD - Entities
Entities are used to define shortcuts to special characters within the XML
documents. Entities can be primarily of four types −
Built-in entities
Character entities
General entities
Parameter entities
Entity Declaration Syntax
In general, entities can be declared internally or externally. Let us understand each
of these and their syntax as follows −
Internal Entity
If an entity is declared within a DTD it is called as internal entity.
Syntax
Following is the syntax for internal entity declaration −
<!ENTITY entity_name "entity_value">
In the above syntax −
entity_name is the name of entity followed by its value within the double quotes or
single quote.
entity_value holds the value for the entity name.
The entity value of the Internal Entity is de-referenced by adding prefix & to the
entity name i.e. &entity_name.
Example
Following is a simple example for internal entity declaration −
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>
<!DOCTYPE address [
<!ELEMENT address (#PCDATA)>
<!ENTITY name "Tanmay patil">
<!ENTITY company "TutorialsPoint">
<!ENTITY phone_no "(011) 123-4567">
]>
<address>
&name;
&company;
&phone_no;
</address>
In the above example, the respective entity
names name, company and phone_no are replaced by their values in the XML
document. The entity values are de-referenced by adding prefix & to the entity
name.
Save this file as sample.xml and open it in any browser, you will notice that
the entity values for name, company, phone_no are replaced respectively.
External Entity
If an entity is declared outside a DTD it is called as external entity. You can
refer to an external Entity by either using system identifiers or public identifiers.
Syntax
Following is the syntax for External Entity declaration −
<!ENTITY name SYSTEM "URI/URL">
In the above syntax −
name is the name of entity.
SYSTEM is the keyword.
URI/URL is the address of the external source enclosed within the double or single
quotes.
Types
You can refer to an external DTD by either using −
System Identifiers − A system identifier enables you to specify the location of an
external file containing DTD declarations.
As you can see it contains keyword SYSTEM and a URI reference pointing to
the document's location. Syntax is as follows −
<!DOCTYPE name SYSTEM "address.dtd" [...]>
Public Identifiers − Public identifiers provide a mechanism to locate DTD
resources and are written as below −
As you can see, it begins with keyword PUBLIC, followed by a specialized
identifier. Public identifiers are used to identify an entry in a catalog. Public
identifiers can follow any format; however, a commonly used format is
called Formal Public Identifiers, or FPIs.
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
Example
Let us understand the external entity with the following example −
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>
Tanmay Patil
</name>
<company>
TutorialsPoint
</company>
<phone>
(011) 123-4567
</phone>
</address>
Below is the content of the DTD file address.dtd −
<!ELEMENT address (name, company, phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Built-in entities
All XML parsers must support built-in entities. In general, you can use these
entity references anywhere. You can also use normal text within the XML
document, such as in element contents and attribute values.
There are five built-in entities that play their role in well-formed XML, they are −
ampersand: &
Single quote: '
Greater than: >
Less than: <
Double quote: "
Example
Following example demonstrates the built-in entity declaration −
<?xml version = "1.0"?>
<note>
<description>I'm a technical writer & programmer</description>
<note>
As you can see here the & character is replaced by & whenever the processor
encounters this.
Character entities
Character Entities are used to name some of the entities which are symbolic
representation of information i.e characters that are difficult or impossible to type
can be substituted by Character Entities.
Example
Following example demonstrates the character entity declaration −
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>
<!DOCTYPE author[
<!ELEMENT author (#PCDATA)>
<!ENTITY writer "Tanmay patil">
<!ENTITY copyright "©">
]>
<author>&writer;©right;</author>
You will notice here we have used © as value for copyright character.
Save this file as sample.xml and open it in your browser and you will see that
copyright is replaced by the character ©.
General entities
General entities must be declared within the DTD before they can be used
within an XML document. Instead of representing only a single character, general
entities can represent characters, paragraphs, and even entire documents.
Syntax
To declare a general entity, use a declaration of this general form in your DTD −
<!ENTITY ename "text">
Example
Following example demonstrates the general entity declaration −
<?xml version = "1.0"?>
<!DOCTYPE note [
<!ENTITY source-text "tutorialspoint">
]>
<note>
&source-text;
</note>
Whenever an XML parser encounters a reference to source-text entity, it will
supply the replacement text to the application at the point of the reference.
Parameter entities
The purpose of a parameter entity is to enable you to create reusable
sections of replacement text.
Syntax
Following is the syntax for parameter entity declaration −
<!ENTITY % ename "entity_value">
entity_value is any character that is not an '&', '%' or ' " '.
Example
Following example demonstrates the parameter entity declaration. Suppose you
have element declarations as below −
<!ELEMENT residence (name, street, pincode, city, phone)>
<!ELEMENT apartment (name, street, pincode, city, phone)>
<!ELEMENT office (name, street, pincode, city, phone)>
<!ELEMENT shop (name, street, pincode, city, phone)>
Now suppose you want to add additional eleement country, then then you need to
add it to all four declarations. Hence we can go for a parameter entity reference.
Now using parameter entity reference the above example will be −
<!ENTITY % area "name, street, pincode, city">
<!ENTITY % contact "phone">
Parameter entities are dereferenced in the same way as a general entity reference,
only with a percent sign instead of an ampersand −
<!ELEMENT residence (%area;, %contact;)>
<!ELEMENT apartment (%area;, %contact;)>
<!ELEMENT office (%area;, %contact;)>
<!ELEMENT shop (%area;, %contact;)>
When the parser reads these declarations, it substitutes the entity's replaceme
XSL (Extensible Stylesheet Language)
What is XSL (Extensible Stylesheet Language)?
XSL (Extensible Stylesheet Language) is a family of standards that specifies
how to define Extensible Markup Language (XML) document transformation and
presentation. The standards are published by the World Wide Web Consortium
(W3C), an international community that develops specifications related to web
architecture, design, applications and other web technologies.