Sunteți pe pagina 1din 107

Web Technologies

Linear Text and Hyper Text: Linear text is a term used to describe any text where there is a defined beginning and a linear progression to the end most books are organized with this expectation. The World Wide Web, however, is organized very differently. Hyper Text is where the user simply selects the next information of interest and is immediately transported to that new location. WWW The World Wide Web is a vast collection of information that is spread across hundreds of thousands of computers around the world. When you access a document on the Web, there's a lot going on behind the scenes. The World Wide Web is a distributed network. That means there is no central computer for the WWW. Any server on the Web can be accessed directly by any client. If a server on the World Wide Web malfunctions, it doesn't affect the performance of other servers. Users navigate the World Wide Web through the use of hypertext links. When you select or click on a hypertext link, you go to another area on the Internet. Almost all of the documents on the Web are interconnected through the use of hypertext links. Most of the documents on the World Wide Web are written in Hypertext Markup Language (HTML). HTML provides instructions for the client software on how the document should be displayed. HTML also contains information about how to link up to other documents on the Web. If you've ever worked with other markup languages such as troff or LaTeX, or even older DOS-based word processors where you put in special codes for things such as "turn on boldface," this won't seem all that unusual. HTML HTML means Hyper Text Markup Language. HTML is based on SGML (Standard Generalized Markup Language), a much bigger document-processing system. Original HTML was developed by Tim Berners-Lee in 1990. Writing in a markup language means that you start with the text of your page and add special tags around words and paragraphs. The tags indicate the different parts of the page and produce different effects in the browser. Every HTML Program has a standard structure. The entire web page is enclosed in <HTML> and </HTML>, which are called open HTML tag and closed HTML tag. Within these tags two distinct sections are created using <HEAD> tags and <BODY> tags. <!DOCTYPE HTML PUBLIC HTML 4.0> <HTML> <HEAD> <TITLE> . . . </TITLE> <BODY> . . . </BODY> <META> . . . </META> </HEAD> <BODY> ... <ADDRESS> . . . </ADDRESS> </BODY> </HTML>
Page No. 1

Head section provides about the title, base and meta information. The body section contains the actual information which includes text, graphics and formatting. Fir the cementation text type we use comment tag <!>. <TITLE> tag provides title for out web page. A title should be short and descriptive. In some browsers, the title will appear in title bar of window. The title is used for search indexes as well in browser history lists and book marks. <META> tag provides meta information about the web page. <BASE> tag attribute targets the name of the window or frame in which all the links on the page should open by default. <BODY> tag attribute takes formatted information of the web page and optionally contains <ADDRESS> tag which provides footer information about the we page. This displays the text immediately after the last line of the information in Italic Style. Getting Started: To get started writing HTML, you're not going to need a Web server, a Web provider, or even a connection to the Web itself. All you really need is something to create your HTML files, and at least one browser to view them. You can write, link, and test whole suites of Web pages without even touching a network. First, you'll need a text editor. A text editor is a program that saves files in ASCII format. ASCII format is just plain text, with no font formatting or special characters. On UNIX, vi, emacs, and pico are all text editors. On Windows, Notepad, Microsoft Write, and DOS edit are good basic text editors. Open up that text editor, and type the following code. You don't have to understand what any of this means at this point. This is just a simple example to get you started <HTML><HEAD> <TITLE>My Sample HTML page</TITLE></HEAD> <BODY> <H1>This is an HTML Page</H1> </BODY></HTML> After you create your HTML file, save it to disk. Remember that if you're using a word processor, do Save As and make sure you're saving it as text only. When you pick a name for the file, there are two rules to follow:

The filename should have an extension of .html (.htm on DOS or Windows systems that have only three-character extensions), for example, myfile.html or text.html or index.htm. Use small, simple names. Don't include spaces or special characters (bullets, accented characters)-just letters and numbers are fine.

View the result. Now that you have an HTML file, start up your Web browser. You don't have to be connected to the network since you're not going to be opening pages at any other
Page No. 2

Web Technologies

site. Your browser or network connection software may complain about the lack of a network connection, but usually it will eventually give up and let you use it anyway. Once your browser is running, look for a menu item or button labeled Open Local, Open File, or maybe just Open. It's a menu item that will let you browse your local disk. The Open File command (or its equivalent) tells the browser to read an HTML file from your disk, parse it, and display it, just as if it were a page on the Web. Using your browser and the Open Local command, you can write and test your HTML files on your computer in the privacy of your own home. HTML Tags: The idea here is that most documents have common elements-for example, titles, paragraphs, or lists. Before you start writing, therefore, you can identify and define the set of elements in that document and give them appropriate names. Tags are instructions that are embedded directly into the text of the document. An HTML tags begin with an angle bracket [<] and end with a closing angle bracket [>]. HTML rags can be two types, paired tags and singular tags. A tag is said to be a paired tag if it has along with a companion end tag. The effects of the paired tag are applied only to the text they contain. For example the <BODY> tag is paired tag. A singular tag does not have a companion tag. These types of tags are also called as standard-alone tag. For example <BR> tag is singular tag. HTML codes which are enclosed between brackets are not case sensitive. The first word or character that appears inside the < opening bracket is called the element. An element is a command that tells the browser to do something, such as <FONT>. Properties of the tags: Word that follows the element and are contained inside the > bracket of the opening tag are called Properties. Each property of an element is a pair or attribute and value. Properties are not repeated and are separated by a space, Each attribute is assigned a value by an equal sign. The value of the attribute is contained in quotes. In the following example the element is FONT, property is color denoted by the attribute COLOR, and the value of the attribute is BLUE can be defined as follows: Eg. <FONT COLOR =BLUE> This text would be blue </FONT> Most HTML elements have more than one attribute Eg: . <FONT COLOR =BLUE SIZE = +1> This text would be blue and size larger than the normal </FONT> The value of an attribute can be a number value like specifying the size of a font

Page No. 3

Web Technologies

HEAD: The HTML head tag defines a block where authors can declare information about the document, as the title, description, keywords, etc., as well as other data that's not considered to be document content. Browsers don't usually render this information (with the exception of the title). The head block is declared before the body . BODY: The HTML body tag embeds all documents renderable content. Between these tags are all the visual (for visual browsers) elements of the document. The presentational attributes for the HTML body tag have been deprecated, since style sheets became a preferred way to define the visual style of a document. Bgcolor: Defines a color to be used as a background Background: The value of this attribute refers to the location of an image resource, that will be used as background. The image usually tiles the background. Text: Sets the foreground color for text. Link: Sets the color of text marking unvisited hypertext links Vlink: Sets the color of text marking visited hypertext links. Alink: Sets the color of text marking visited hypertext links. FORMATTING TAGS : When an HTML page is parsed by a browser, any formatting you may have done by hand-that is, any extra spaces, tabs, returns, and so on-are all ignored. The only thing that formats an HTML page is an HTML tag. If you spend hours carefully editing a plain text file to have nicely formatted paragraphs and columns of numbers, but you don't include any tags, when you read the page into an HTML browser, all the text will flow into one paragraph.
<HTML><HEAD> <TITLE>No Format </TITLE> </HEAD> <BODY>

HTML means Hyper Text Markup Language. HTML is based on SGML. Original HTML was developed by Tim Berners-Lee in 1990.
</BODY></HTML>

Basic Text Formatting Tags: Paragraph Tag [<P>] A blank line always separates paragraphs in the text. The tag provides this functionality is <P>. On encountering this tag the browser, moves on to a new line, skipping one line between the previous line and the new line.
Page No. 4

Web Technologies
<HTML><HEAD> <TITLE>Paragraph demo </TITLE> </HEAD> <BODY>

HTML means Hyper Text Markup Language. HTML is based on SGML.<P> Original HTML was developed by Tim Berners-Lee in 1990.

The <P> tag always creates a simple, left-justified paragraph. You can change the justification of the paragraph with the ALIGN attribute. To change the alignment of a paragraph, put the ALIGN statement in the paragraph tag, followed by the type of justification you want. To create a right-justified paragraph, type <P ALIGN=RIGHT>. To create a centered paragraph, type <P ALIGN=CENTER>. To create a paragraph that is justified on both sides, type <P ALIGN=JUSTIFY>. You can also create a left-justified paragraph by typing <P ALIGN=LEFT>. By default, the Web browser will wrap lines of text to keep the entire paragraph in view. You have the option of turning off word wrapping by including the NOWRAP command in the paragraph tag. To turn off word wrapping in a paragraph, type <P NOWRAP > Line Break [<BR>] When text needs to start a new line and not continue on the same line, the <BR> tag should be used. This tag simply changes line of the text and start on the next line without skipping a blank line.
<HTML><HEAD> <TITLE>Line Break </TITLE> </HEAD> <BODY> HTML means Hyper Text Markup Language. HTML is based on SGML.<BR> Original HTML was developed by Tim Berners-Lee in

</BODY></HTML>

1990. </BODY></HTML>

Head Formals [<H1> to <H6>] HTML supports Six different levels of headings. The highest level header format is <H1> and the lowest level header <H6>. All the style appear in BOLD face and the size of the heading depends on the level we chosen.

Page No. 5

Web Technologies

<HTML><HEAD> <TITLE> Level- 1 Paragraph </TITLE> </HEAD><BODY> <H1> Berners-Lee </H1> </BODY></HTML>

<HTML><HEAD> <TITLE> Level-2 Paragraph </TITLE> </HEAD><BODY> <H2> Berners-Lee </H2> </BODY></HTML>

<HTML><HEAD> <TITLE>Level-3 Paragraph</TITLE> </HEAD><BODY> <H3> Berners-Lee </H3> </BODY></HTML>

<HTML><HEAD> <TITLE>Level-4 Paragraph</TITLE> </HEAD><BODY> <H4> Berners-Lee </H4> </BODY></HTML>

<HTML><HEAD> <TITLE>Level-5 Paragraph</TITLE> </HEAD><BODY> <H5> Berners-Lee </H5> </BODY></HTML>

<HTML><HEAD> <TITLE>Level-5 Paragraph</TITLE> </HEAD><BODY> <H6> Berners-Lee </H6> </BODY></HTML>

Page No. 6

Web Technologies

Drawing Lines [<HR>] The Tag <HR> draws lines which are also called horizontal rules. This tag draws a horizontal line across the whole page, where over it spread.
<HTML><HEAD> <TITLE>Horizontal rule</TITLE> </HEAD><BODY> <HR> Berners-Lee </BODY></HTML>

The attributes of the Horizontal rule tag are : 1. WIDTH: Sets the width of the rule. It can be set to a fixed number of pixels or to a percentage of the available screen width
<HTML><HEAD> <TITLE>Horizontal rule</TITLE> </HEAD><BODY> <HR WIDTH=50> Berners-Lee </BODY></HTML>

<HTML><HEAD> <TITLE>Horizontal rule</TITLE> </HEAD><BODY> <HR WIDTH=60%> Berners-Lee </BODY></HTML>

2. Align: Align tag alines the line on the browser screen. Which is by default align to the center of the screen. Value of this attribute are LEFT, RIGHT, CENTER.
<HTML><HEAD> <TITLE>Horizontal rule</TITLE> </HEAD><BODY> <HR WIDTH=50 ALIGN=RIGHT>

Berners-Lee </BODY></HTML>

2. SIZE: Changes the size of the rule.


<HTML><HEAD> <TITLE>Horizontal rule</TITLE> </HEAD><BODY> <HR SIZE=4>

Berners-Lee </BODY></HTML>

Page No. 7

Web Technologies

BLOCKQUOTE: To place an entire section of text apart from the rest, use the <BLOCKQUOTE> and </BLOCKQUOTE> tag pair. This tag, used in place of a paragraph tag, will offset an entire paragraph from the main body of text, usually by indenting it and adding extra spaces to the top and bottom. It is commonly used to highlight long quotations and passages. TEXT STYLES: BOLD: To create bold text, insert <B> and </B> tags. Any text falling between these two tags will appear in boldface type ITALIC: To create italic text, insert an <I> tag in the document, followed by a </I> tag. Any text between these two tags will be displayed in italics when viewed by a browser. UNDER LINE:Underlined text can be displayed using the <U> and </U> tag pair. You should use these tags only when absolutely necessary, as underlined text is not widely supported by Web browsers. SMALL FONT: When using superscript numbers to indicate footnotes, try adding the <SMALL> and </SMALL> tags to make the footnote numbers smaller than the normal text. BIG FONT: When using superscript numbers to indicate footnotes, try adding the <SMALL> and </SMALL> tags to make the footnote numbers smaller than the normal text. TYPEWRITER TEXT: To create text that is displayed in a monospaced font (such as Courier), use the <TT> and </TT> tags. Text falling between these two tags will be displayed in a fixedwidth font, similar to the output from a teletype machine or typewriter. STRIKEOUT: To create strike-through text, which is text with a single horizontal line running through it, use the <STRIKE> and </STRIKE> tags SUPERSCRIPT AND SUBSCRIPT: You can also format text as either superscript or subscript, which is text that appears slightly above or below the current line, respectively. Superscript and subscript numbers are often used in mathematical equations or to indicate footnotes. Using the <SUP> and </SUP> tags will mark text as superscript (slightly above the current line). <SUB> and </SUB> will mark text as subscript (slightly below the current line) EMPASSED: When you want to add importance to a section of text, you can use the logical style tag called emphasis. Using the <EM> and </EM> tags will usually display the indicated text in italics. However, remember that with logical tags, the actual
Page No. 8

Web Technologies

appearance of the text is determined by the end user's Web browser, not your HTML document. STRONG: If a particular section of text is very important, you can mark it with strong emphasis by using the <STRONG> and </STRONG> tag pair. Most browsers tend to display strongly emphasized text in boldface. CODE: The <CODE> and </CODE> tags indicate that the text is to be presented as an example of programming code. In most browsers, this text will be displayed in a monospaced font, such as Courier. The <CODE> tags are used extensively in interactive computer manuals. SAMP: The <SAMP> and </SAMP> tags are very similar to the <CODE> tags, and are used to indicate sample text that isn't specifically programming code. Most Web browsers will handle both sets of tags in the same way. KBD: The <KBD> and </KBD> tags indicate text that is supposed to be typed in by the reader. By default, most browsers will display this text in a similar fashion to the <SAMP> tag. CITE: The <CITE> and </CITE> tags are used to insert a citation to give credit for a short quotation in the body of the document. Citations are typically displayed in italics. DEF: The <DFN> and </DFN> tags are used to highlight the defining instance of a term. This is a word or phrase that is being defined in the context of the paragraph in which it appears. PRE: Preformatted text is a great way to create a quick and dirty table of data, such as names and phone numbers. However, HTML 3.2 has full table support, and in most cases you'll want to use real tables whenever possible. Another good use for the <PRE> and </PRE> tags is to display samples of Internet e-mail or newsgroup posts in your HTML document. These messages often have specific layouts that are difficult to reproduce in straight HTML. Just cut and paste the original message into Notepad and then place the <PRE> and </PRE> tags at the beginning and end, respectively. 1. To begin a section of preformatted text, type <PRE>. 2. Now type the section of text exactly how you want it to appear. It's a good idea to limit the length of your lines to 65 characters or less, so that you can accommodate the screen width of most browsers. (Remember that browsers will not word wrap preformatted text.)
Page No. 9

Web Technologies

3. When you're finished entering your preformatted text, type </PRE> to mark the end of the section IMATE TAG: The two most common image file formats in use on the World Wide Web are GIF (.GIF) and JPEG (.JPG) files. The GIF format is directly supported by every graphical Web browser, while JPEG is still gaining acceptance as a standard image format on the World Wide Web. Although both GIF and JPEG files can be used in your HTML documents, there are a few important differences between the two formats. Once you've got the image file prepared, the next step is to place it in your HTML document with markup tags. Images in HTML are included by using the <IMG> tag. This page will cover the basic elements and attributes used when including an <IMG> tag in your document. 1. Locate the place in your document where you'd like to insert the image. 2. You can place images in your HTML document by using the <IMG> tag. To insert an image into your HTML document, type <IMG>. There is no closing </IMG> tag. 3. Now you need to specify the URL of the image to load by placing the SRC (source) attribute within the <IMG> tag. If you store your images in the same directory as your HTML files, the URL can simply be the file name of the image. For example, to insert a GIF file named logo.gif into your HTML document, you would type <IMG SRC="logo.gif">. 4. To link to images that are not in the same directory as the HTML document, use relative URLs to locate them. For example, if you stored the above logo.gif file in a subdirectory called images in your HTML documents folder, you would type <IMG SRC="images/logo.gif">. 5. The ALT attribute allows you to create alternate text for your image that will be shown to users who have browsers that do not support graphics. Some browsers will also display the alternate text while the image is loading. To specify the alternate text, type ALT=, followed by the text in quotes. For example, adding alternate text would change the above image tag to <IMG SRC="images/logo.gif" ALT="The LawnBirds, Inc. logo in stunning 3-D.">. Tip Sheet If you want to link to images that are not your own, be sure to get permission from the copyright holder first. You should always use ALT to specify alternate text for an image, so that users without graphical capability will understand what the image is showing. TABLE: Tables in HTML page allow us to organize information in a row and column format. The horizontal and vertical lines in a table are called dividers. Tables are created using the <TABLE> tag. Inside the table tag the <TR> tag is the table row tag. The items in a row are specified using the table data tag <TD>. Tables can include headers in a format. These headers can be given using <TH> tag. A table can be
Page No. 10

Web Technologies

displayed a caption using the <CAPTION> tag. The default alignment of the caption tag is top center of the table. But it can also be aligned to bottom of the table using align property value as bottom. <COLS> and <COLSGROUP> are used to set the common properties of the columns of the table. <THEAD> and <TFOOT> are used to set the table header and footer rows, reset will be defined as <TBODY>. Attributes of the TABLE tag are: Align: Horizontal alignment, values can be left, center, right, or justify. Valign: Vertical alignment, values can be top, middle or bottom. Border: Controls the border to be placed around the table with the amount in pixels. Bordercolor: Sets the color to the border. Height: Sets the height of the table. Width: Sets the width of the table, Frame Sets the Attributes of the TD, TH tags: Colspan: Used to keep up more than one column as a single column. Rowspan: Used to keep up more than one row as a single row. Cellpadding: Sets the distance between the data in a cell. Cellspacing: Sets the spacing between adjacent cells. Hspace Sets horizontal space to the text in a cell ( left, right) Vspace Sets vertical space to the text in a cell (top, bottom)
<HTML> <HEAD> <TITLE>table design</TITLE> </HEAD> <BODY> <TABLE BORDER=2> <CAPTION><B>STOCK TABLE<B></CAPTION> <TR><TD ROWSPAN=2>ITEM NO <TD ROWSPAN=2>DESCRIPTION <TD ROWSPAN=2>QTY <TD COLSPAN=2 ALIGN=CENTER>RATE <TR> <TD>Rs.<TD>Ps. <TR> <TD>101<TD>FLOPPY BOX <TD>20 <TD ALIGN=RIGHT>100 <TD>00 <TR> <TD>102<TD>PRINTER<TD>3 <TD ALIGN=RIGHT>6000<TD>00 <TR> <TD>103<TD>HARD DISKS<TD>6 <TD ALIGN=RIGHT>3000<TD>00</TR> </BODY> </HTML>

Page No. 11

Web Technologies

MARQUEUE: The <MARQUEE> </MARQUEE> element defines text that is displayed in an animated region of the browser. Width: Width of the marquee in pixels Height : Height of the marquee in pixels Loop: Defines how many times the text will repeat through the space. Bgcolor: Defines the background color. Behavior: Defines how the text should move in the marquee as slide, scroll, alternate Direction Down, up, left, right Scrolldelay Sets the number of milliseconds before refreshes. Scrollamount Sets the amount to be scrolled Hspace Sets horizontal space to the text in a marquee ( left, right) Vspace Sets vertical space to the text in a marquee (top, bottom) Width Sets the width of the marquee. LINKS: The Link text part is the word or phrase that your readers will click on to jump to whatever page you specified in the Address part. A quick click on a particular link and you're off on a journey to a whole new world. Users navigate the Web by clicking on the links that HTML authors provide. Hypertext links are a crucial part of HTML-which, after all, is short for Hypertext Markup Language. Hyperlinks connect two different documents. You can link to one of your own documents or to any other document on the World Wide Web. You can even link to a different section in the same document. To make a link to another document, you need to use a special type of HTML tag known as an anchor tag, also commonly known as a link tag. Locate the place in your HTML document where you want to insert the hypertext link. Type <A HREF=", followed by the URL of the document you want to link to. However, if you're linking to different documents on the same Web server (usually your own), you don't always need to use the full URL. You can use relative path names. Then close the tag by typing ">.Type some descriptive text (also known as the link text) after the anchor tag to let readers know something about where this link will take them. Finish the anchor tag by typing </A> on the same line. Once you've created your link, check to make sure it works by clicking on it while using your Web browser. Note that by default, most Web browsers display hypertext links as underlined text in a different color than normal text. This lets your readers know that clicking on the text will take them to another document. Notice that when you create a simple link to a Web page using the above technique reader is always taken to the top of the new page. Assigning an ID to an element in your HTML document allows hyper links to point directly to that element instead of
Page No. 12

Web Technologies

to the very top of the page. You can use the ID attribute for most HTML elements, such as paragraphs, headings, and lists. Locate the element you'd like to name with an ID. This can be almost any element in your document, but it is usually a paragraph or heading. Inside the element's opening tag, say for example a paragraph tag <P> just after the letter P, insert a space and type ID=. Your element ID needs a name. The hyperlinks will use this name to take readers directly to this section of your document. In this example, we'll simply name the element "MyParagraph". To create a hyperlink directly to this element, add a pound sign and the ID name inside your hyperlink tag. For example, to link directly to "MyParagraph", a typical hyperlink might look like the one below. <P ID=MyParagraph> IMAGE MAPPINGS: MAP was originally defined to take one or more AREA elements that specify the coordinates of a clickable region on the image. HTML allows images in different documents to use the same MAP definition from just one file, but many browsers do not support this and require the MAP and image elements to be in the same document. The MAP element defines a client-side image map for use with an IMG. MAP's required NAME attribute is used as an anchor for the USEMAP attribute of the IMG element. MAP element to take one or more block-level elements as an alternative to using AREA elements. The AREA element defines a map region in a client-side image map. Each map region is a piece of the image that may have a different action when clicked. The SHAPE and COORDS attributes of AREA specify what part of the image is included in the region. The default SHAPE value is rect, which defines a rectangular region using COORDS="left, top, right, bottom". Other SHAPE values are default, which specifies the entire image; circle, which specifies a circular region using COORDS="center-x, center-y, radius"; poly, which specifies a polygonal region using COORDS="x1, y1, x2, y2, ..., xN, yN". Coordinate values are relative to the top left corner of the object and may be expressed as pixels or percentages. A percentage radius value for circular regions is calculated relative to the smaller of the object's width and height. If two or more regions overlap, the earliest specified region takes precedence. The HREF attribute specifies a link to another resource, such as an HTML document or a JPEG image. The TITLE attribute can be used to briefly describe the contents of the link and is rendered as a "tooltip" by some visual browsers. The Boolean NOHREF attribute indicates that the region has no link.
Page No. 13

Web Technologies

The required ALT attribute provides alternate text for those not loading images. Effective ALT text should generally give the function of the map region rather than a description of the region. Good ALT text is an important accessibility feature for users who do not load images. The TARGET attribute is used with frames to specify the frame in which the link should be rendered. If no frame with such a name exists, the link is rendered in a new window unless overridden by the user. Special frame names begin with an underscore: _blank renders the link in a new, unnamed window _self renders the link in the current frame (useful for overriding a BASE TARGET) _parent renders the link in the immediate FRAMESET parent _top renders the link in the full, unframed window In HTML 4, the TARGET attribute value is case-insensitive, so that _top and _TOP both have the same meaning. However, most browsers treat the TARGET attribute value as case-sensitive and do not recognize _TOP as having the special meaning of _top. LISTS: Everyone makes lists. Whether you use them for groceries, to-do items, or holiday gifts and cards, lists are an important part of your life. Lists are also important on the World Wide Web. The environment of the Web calls for information to be presented in a concise and timely manner. As an HTML author, you have many choices for how to create and present lists. In this chapter, we'll look at ways to create unordered lists, ordered (numbered) lists, and a special type of list known as a definition list. You'll also learn how to combine multiple levels of lists. Lists are ideal vehicles for delivering all kinds of information on line. All the lists are formatted by a principle quote to specify what sort of list can be created (OL-ordered list, UL- unordered list, and DL-definition list) and a secondary quote to specify what sort of item (LI-list item, DT- Definition term) we want to create. Unordered Lists: The simplest list in HTML is the unordered, or bulleted, list. This is ideal for listing items that have no particular hierarchy or order of importance. Unordered lists are very common on the Web and are used to convey items of note in a quick and concise manner. Web browsers usually place bullets or other markers in front of each item in an unordered list. Begin the unordered list by typing <UL>, and then press Enter. The <UL> tag tells the Web browser to treat this section of text as an unordered list. Unordered lists will usually be indented from the main document and list items will be formatted with bullets. The size and type of bullets used are determined by the Web browser.

Page No. 14

Web Technologies

To create the first item in your list, type <LI>. Then type the text of the item itself. <LI> is an open tag, which means that you do not need to type </LI> at the end of each item. Continue typing <LI> followed by text for each item in your list. Press Enter after each item. Finish the unordered list by typing </UL>. <UL> tag type attribute is used to specify the type of the list by TYPE attribute, possible values of type are disc ( to draw a filled circle which is a default one), circle ( to draw a non filled circle and square (to draw non filled square). Nesting order of the list will be disc, circle then square by default. Ordered Lists: An ordered (numbered) list items begin by typing <OL>, and then press Enter. The <OL> tag tells the Web browser to treat this section of text as an ordered list. Ordered lists will usually be indented from the main document and list items will be formatted with numbered automatically. You have the choice of setting the TYPE attribute to one of the five number styles. Specify bullet type by adding type= followed by one of: "1 a A i I". TYPE Number Style 1 Arabic Numbers a Lower Alpha A Upper Alpha i I Lower Roman Upper Roman 1, 2, 3.. a, b, c A, B, C i, ii, iii I, II, III

You can also specify a start number of an order list. The value of the START attribute is always an Arabic Numbers. Specify starting number by adding start=#. You can also change the sequence of list order in middle by specifying new value with VALUE attribute of <li>. Definition List: Definition list is different from others. Each item in DL consists of one or more Definition Terms (DT element), followed by one or more Definition Description (DD element), the definition is always placed on the next line to emphasize the relation. Note: You can next the list by inserting UL, OL etc., inside a list item (LI). Menu List: The MENU element defines a menu list. The element contains one or more LI elements that define the actual items of the list. The LI elements must not contain block-level elements, which prevents MENUs from being nested. MENU is deprecated in HTML 4 in favor of UL. Directory List: The DIR element defines a directory list. The element contains one or more LI elements that define the actual items of the list. The LI elements must not contain
Page No. 15

Web Technologies

block-level elements, which prevents DIRs from being nested. DIR is deprecated in HTML 4 in favor of UL. FRAMES: By dividing a page, called Frameset into frames we can allow visitor to see more than one page at a time. Each frame contains its own web page. A Frame set is a window which contains individual panes. Each pane shows different information. We can design as many panes as we required, set the name, size, borders and scrollbars of each pane. We can assign frame contents using URL. The HTML tag recognizable unique regions using the <FRAMESET></FRAMESET> tags. The <FRAMESET> tag require one of the two attributes ROWS/COLS depending on whether the screen has to be divided rows or columns or both. Once the browser screen is divided into rows and columns, each unique section defined can be loaded with <FRAME> tag, which can take attributes. : This attribute defines the address of the initial content for the frame. : Assigns a name to the frame. This name may be used as the value of the "target" attribute in links and forms. Border : Decides if a border (separator) will be drawn for this frame. The value "1" tells the browser to draw a border for this frame, while the value "0" not to draw it. Note thatfor two adjacent frames, both "frameborder" attributes must be set to "0" if you want the border between them to be invisible. Marginheight: Specifies the distance between the left margin and the content, as well as the distance between the right margin and the content. Marginwidth: Specifies the distance between the top margin and the content, as well as the distance between the bottom margin and the content. Noresize : When present, this attribute indicates that users should not be able to change the frame's size Scrolling : Decides how scrolling will be shown for this frame. Possible values areauto,yes and no Sample Program:
<HTML> <HEAD> <TITLE>Frame Demo</TITLE> </HEAD> <FRAMESET COLS="30%,*"> <FRAME NAME="ONE" SRC="ONE.HTML"> <FRAMESET ROWS="20%,*"> <FRAME NAME="TWO" SRC="TWO.HTML"> <FRAME NAME="THREE" > </FRAMESET> </FRAMESET> </HTML> <HTML> <HEAD> <TITLE>two.html file</TITLE> </HEAD> <BODY><CENTER> <H2>SICET EN G . COLLEGE</H2></CENTER> </BODY> </HTML>

Src Name

Page No. 16

Web Technologies
<HTML> <HEAD> <TITLE>one.html file</TITLE> </HEAD> <BODY><B> <OL> <LI> List of Cources <LI> Faculties <LI> Fee structure </OL></B> </BODY>

FO</MTML> RH S A form is an area that can contain form elements. Form elements are elements that allow the user to enter information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.) in a form. A form is defined with the <form> tag. <form> . input elements . </form> Input The most used form tag is the <input> tag. The type of input is specified with the type attribute. The most commonly used input types are explained below. Text Fields Text fields are used when you want the user to type letters, numbers, etc. in a form. <form> First name:<input type="text" name="firstname" /><br /> Last name:<input type="text" name="lastname" /> </form>

How it looks in a browser: First name: Last name: Note that the form itself is not visible. Also note that in most browsers, the width of the text field is 20 characters by default Password Field Passwod fields are used when user want to type letters, numbers, etc. And at the same time information typed by the user cant be displayed, they are masked with a character. In a form <input type="password" /> defines a password field: The characters in a password field are masked (shown as asterisks or circles). <form> Password: <input type="password" name="pwd" /> </form>
Page No. 17

Web Technologies

How the HTML code above looks in a browser: Password: Radio Buttons Radio Buttons are used when you want the user to select one of a limited number of choices. <form> <input type="radio" name="sex" value="male" /> Male <input type="radio" name="sex" value="female" /> Female </form> How it looks in a browser: Male Female Note that if only one option can be chosen then. Checkboxes Checkboxes are used when you want the user to select one or more options of a limited number of choices. <form> I have a bike: <input type="checkbox" name="vehicle" value="Bike" /> I have a car:<input type="checkbox" name="vehicle" value="Car" /> </form> How it looks in a browser: I have a bike: I have a car: Submit A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input: <input type="submit" value="Send form">
How it looks in a browser

without value the submit button look like this R es et A reset button resets all controls in the form, clearing the user input and returning controls to their initial values. <input type="reset" value="Reset form">
How it looks in a browser

The <label> tag defines a label for an input element.


Page No. 18

Web Technologies

Label The label element does not render as anything special for the user. However, it provides a usability improvement for mouse users, because if the user clicks on the text within the label element, it toggles the control. The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together. <form> <label for="male">Male</label> <input type="radio" name="sex" id="male" /> <label for="female">Female</label> <input type="radio" name="sex" id="female" /> </form>
How it looks in a browser

Select control element This control offers the user a pull-down menu option from which to choose one option. <select name="age"> <option>18-40</option> <option>41-65</option> <option>65 upwards</option> </select>
How it looks in a browser

When used with the size attribute, the select control renders as a multi-select scrolling list that displays the number of entries that is specified as the value of the size attribute. Textarea This element creates a multi-line input control, allowing users to type in and view larger amounts of data. The author specifies the geometry of the area by including the rows and cols attributes. <textarea name="furtherdetails" rows="6" cols="30"></textarea>
Page No. 19

Web Technologies How it looks in a browser

Button The <button> tag defines a push button. A button is marked up as follows: <button type="button">Click Me!</button>
How it looks in a browser

Inside a button element you can put content, like text or images. This is the difference between this element and buttons created with the input element. Fieldset The <fieldset> tag is used to logically group together elements in a form. The <fieldset> tag draws a box around the related form elements. The <legend> tag defines a caption for the fieldset element. <fieldset> <legend>Personalia:</legend> Name: <input type="text" size="30" /><br /> Email: <input type="text" size="30" /><br /> Date of birth: <input type="text" size="10" /> </fieldset> How it looks in a browser

Legend: The <legend> tag defines a caption for the fieldset element. <fieldset> <legend>Personalia:</legend> Name: <input type="text" size="30" /><br /> Email: <input type="text" size="30" /><br /> Date of birth: <input type="text" size="10" /> </fieldset>
Page No. 20

Web Technologies

How it looks in a browser

Element Form

Attribute Name Action M e t hod Target Type Name Disabled Readonly Size Value

Description Name of the form Where to send data Mode of send Where to open url Type of Input Name of the element Disabled an input Read only an input Width of the input field Value of input element

Input

Value Name of the form url of server script Get, Post _blank, _self, _parent, _top or framename Button, checkbox, file, hidden, image, password, radio, reset, submit, text Name of the element 19

Maxlength SRC URL of Image Align Alt File Accept Checkbox/radio checked Preselection of element

Text/Password Image

Default initial value : Text,password,hidden Text on the button: button, reset, submit Associated Value: checkbox,radio,image, option No of characters

Mime type : image/gif Checked

TextArea Select Option Optiongroup Fieldset Legend Button

Rows Cols Size Multiple Selected Label

Visible hight (rows) Visible width (characters) No of visible options Multiple selection Options of the list Default selection Visible option Group the list options Grouping elements Caption of the field Push button

2 19

Page No. 21

Web Technologies

&amp; &trade; &reg; &copy; &quot; &#147; &#148; &frasl; &lt; &gt; &raquo; &laquo; &#151; &pound; &deg; &frac14; &frac12; &frac34; &middot; &iexcl; &spades; &clubs; &hearts; &diams;

SPECIAL CHARACTERS & Ampersand Trademark Registered trademark Copyright " Double quote marks Left quote Right quote / Forward slash < Less than arrow > Greater than arrow Right pointing double angle quotation mark Left pointing double angle quotation mark Em-dash Pound sign (GBP currency) 30 Degree Quarter Half Three quarters Middle dot Inverted exclamation mark Black spade suit Black club suit Black hearts suit Black diamond suit

CASCADING STYLE SHEETS CSS Lets us to assign several properties at once to all the elements It is a set of formatting instructions Common format for all web pages Saves Time Easy to Change Easy to apply Overrides earlier definitions Controls text in a way that HTML cannot.

There are three mechanisms to apply CSS 1. Inline Style Sheets 2. Internal Style Sheets 3. External Style sheets

Page No. 22

Web Technologies

INLINE STYLE SHEETS Style information can be included inline i.e. with in the tag of HTML elements. It can also be called as local styles. All style elements are declared with in the <BODY> tag. Syntax: Ex: STYLE = declaration Declaration => property: value <BODY> <P STYLE=font-family:Arial> SICET </P> <BODY>

INTERNAL STYLE SHEETS: Internal styles are ideal for individual pages. Style information can be embedded directly with in the document by using the <STYLE> tag. Syntax: <STYLE> SELECTOR{ declarator} . </STYLE> SELECTOR can be any HTML element <HEAD> <STYLE> H1{color:red} </STYLE> </HEAD>

Ex:

EXTERNAL STYLE SHEETS: External style sheets are ideal for giving all the pages on our web site a common look. External style sheet is separate web document which has style definitions, and has an extension .css. This external style sheet can be linked to any web documents via a URL. Style document: <STYLE> H2{color:blue} H3{background : yellow} </STYLE> this document should be saved by giving extension as .css Linking of external document to our present web document can be done as <HEAD> <LINK REL=stylesheet TYPE=text/css HREF=css file path> </HEAD>
Page No. 23

Web Technologies

CLASS AND ID SELECTORS: Any element of the HTML document may have a class associated withit. A class or id gives ability to apply specific patterns the same selector. Ex: <HTML> <HEAD> <STYLE> P.in{color: red} </STYLE> </HEAD> <BODY> <P> SRTIST </P> <P class=in> welcome </P> </BODY> </HTML> Class can also be declared so that it apply to all selectors, .in{color:blue} Use: <H1 class=in> SRTIST</H1> <P class=in>welcome</p> We can also use # decelerator and access it by ID. For flexibility we can also use SPAN and DIV tags CSS Selectors, Properties, and Values For each selector there are 'properties' inside curly brackets, which simply take the form of words such as color, font-weight or background-color. A value is given to the property following a colon (NOT an 'equals' sign) and semicolons separate the properties. body { font-size: 0.8em; color: navy; }

This will apply the given values to the font-size and color properties to the body selector. So basically, when this is applied to an HTML document, text between the body tags (which is the content of the whole window) will be 0.8 ems in size and navy in colour.

Page No. 24

Web Technologies

Lengths and Percentages There are many property-specific units for values used in CSS, but there are some general units that are used in a number of properties and it is worth familiarising yourself with these before continuing. em px pt % em is the unit for the calculated size of a font. So "2em", for example, is two times the current font size(such as font-size: 2em). px is the unit for pixels(such as font-size: 12px). pt is the unit for points(such as font-size: 12pt). % is the unit for percentages(such as font-size: 80%).

Other units include pc (picas), cm (centimetres), mm (millimetres) and in (inches). When a value is zero, you do not need to state a unit. For example, if you wanted to specify no border, it would be border: 0. A web page is not a static, absolute medium. It is meant to be flexible and the user should be allowed to view the web page how, they wish which includes the font size and the size of the screen. Because of this, it is generally accepted that 'em' or '%' are the best units to use for font-sizes (and possibly even heights and widths, rather than 'px', which leads to non-resizable text in most browsers, and should be used sparingly, for border sizes. Colours CSS brings 16,777,216 colours to your disposal. They can take the form of a name, an rgb (red/green/blue) value or a hex code. red Is the same as rgb(255,0,0) Which is the same as rgb(100%,0%,0%) Which is the same as#ff0000 Which is the same as#f00 There are 17 valid predefined colour names. They are aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white, and yellow. transparent is also a valid value. The three values in the rbg value are from 0 to 255, 0 being the lowest level (for example no red), 255 being the highest level (for example full red). These values can also be a percentage. Hexadecimal is a base-16 number system. We are generally used to the decimal number system (base-10, from 0 to 9), but hexadecimal has 16 digits, from 0 to f.

Page No. 25

Web Technologies

The hex number is prefixed with a hash character (#) and can be three or six digits in length. Basically, the three-digit version is a compressed version of the six-digit (#f00 becomes #ff0000, #c96 becomes #cc9966 etc.). The three-digit version is easier to decipher (the first digit, like the first value in rgb, is red, the second green and the third blue) but the six-digit version gives you more control over the exact colour. color and background-color Colours can be applied by using color and background-color (note that this must be the American English 'color' and not 'colour'). A blue background and yellow text could look like this: h1 { color: yellow; background-color: blue; } These colours might be a little too harsh, so you could change the code of your CSS file for slightly different shades: body { font-size: 0.8em; color: navy; } h1 { color: #ffc; background-color: #009; } You can apply the color and background-color properties to most HTML elements, including body, which will change the colours of the page and everything in it. Text You can alter the size and shape of the text on a web page with a range of properties, outlined below: font-family This is the font itself, such as Times New Roman, Arial, or Verdana. The font you specify must be on the user's computer, so there is little point in using obscure fonts. There are a select few 'safe' fonts (the most commonly used are arial, verdana and times new roman), but you can specify more than one font, separated by commas. The purpose of this is that if the user does not have the first font you specify, the browser will go through the list until it finds one it does have. This is useful because different computers sometimes have different fonts installed. So fontfamily: arial, helvetica, for example, is used so that similar fonts are used on PC (which traditionally has arial, but not helvetica) and Apple Mac (which, traditionally, does not have arial and so helvetica, which it does normally have, will be used). Note: if the name of a font is more than one word, it should be put in quotation marks, such as font-family: "Times New Roman".

Page No. 26

Web Technologies

font-size The size of the font. Be careful with this - text such as headings should not just be a paragraph in a large font; you should still use headings (h1, h2 etc.) even though, in practice, you could make the font-size of a paragraph larger than that of a heading. font-weight This states whether the text is bold or not. In practice this usually only works as fontweight: bold or font-weight: normal. In theory it can also be bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800 or 900, but seeing as many browsers may not support them, it's safer to stick with bold and normal. font-style This states whether the text is italic or not. It can be font-style: italic or font-style: normal. text-decoration This states whether the text is underlined or not. This can be: text-decoration: overline, which places a line above the text. text-decoration: line-through, strike-through, which puts a line through the text. text-decoration: underline should only be used for links because users generally expect underlined text to be links. This property is usually used to decorate links, such as specifying no underline with text-decoration: none. text-transform This will change the case of the text. text-transform: capitalize turns the first letter of every word into uppercase. text-transform: uppercase turns everything into uppercase. text-transform: lowercase turns everything into lowercase.text-transform: none I'll leave for you to work out. Text spacing The letter-spacing and word-spacing properties are for spacing between letters or words. The value can be a length or normal. The line-height property sets the height of the lines in an element, such as a paragraph, without adjusting the size of the font. It can be a number (which specifies a multiple of the font size, so '2' will be two times the font size, for example), a length, a percentage or normal. The text-align property will align the text inside an element to left, right, center or justify. The text-indent property will indent the first line of a paragraph, for example, to a given length or percentage. This is a style traditionally used in print, but rarely in digital media such as the web.
Page No. 27

Web Technologies

p{

letter-spacing: 0.5em; word-spacing: 2em; line-height: 1.5; text-align: center; }

Margins and Padding margin and padding are the two most commonly used properties for spacing-out elements. A margin is the space outside of the element, whereas padding is the space inside the element. h2 { font-size: 1.5em; background-color: #ccc; margin: 1em; padding: 3em; }

The four sides of an element can also be set individually. margin-top, margin-right, margin-bottom, margin-left, padding-top, padding-right, padding-bottom and padding-left are the self-explanatory properties you can use. The Box Model Margins, padding and borders are all part of what's known as the Box Model. The Box Model works like this: in the middle you have the content area (let's say an image), surrounding that you have the padding, surrounding that you have the border and surrounding that you have the margin. You don't have to use all of these, but it can be helpful to remember that the box model can be applied to every element on the page, and that's a powerful thing! CSS Borders Borders can be applied to most HTML elements within the body. To make a border around an element, all you need is border-style. The values can be solid, dotted, dashed, double, groove, ridge, inset and outset. border-width sets the width of the border, which is usually in pixels. There are also properties for border-top-width, border-right-width, border-bottom-width and border-left-width. Finally, border-color sets the colour. h2 { border-style: dashed; border-width: 3px; border-left-width: 10px; border-right-width: 10px; border-color: red;

Page No. 28

Web Technologies

This will make a red dashed border around all HTML secondary headers (the h2 element) that is 3 pixels wide on the top and bottom and 10 pixels wide on the left and right (these having over-ridden the 3 pixel wide width of the entire border). More about style definitions: All declarations are case sensitive Declarations can be more than one, if we want to define more than one those can be separated by semicolon. property1:value1; property2:value2; One property can take more than one value by blank space sepration property: value1 value2 value3; Same definitions can be applied to more then one selectors by using coma separator. H1, b {....} We can establish dependence relation among definitions by separating dependent tag and parent tag just by giving a space. B U { .. } Image Declarations: width height border Property px, pt px, pt thin, medium, thick, px none, dotted, dashed, solid, grove, ridge, inset, outset border-right px, pt, vh, thb, trbl px baseline, middle, top, bottom text-top, text-bottom, left right left, right, both, none absolute Value value Definitions

border-top border-bottom padding margin vertical-align float clear position top, bottom, left, right

border-left gap between the image and other element

Removes the text at

Relative

Page No. 29

Web Technologies

Text Declarations: Property text-decoration value underline overline linethrough blink none capitalize uppercase lowercase none px, pt px, pt, % rgb(n), #code, rgb(%,%,%), name color,url length right, left, center, justify pre nowrap normal name italic, oblique, normal bold, light, normal, 100 to 900, bolder, lighter Small, x-small, xx-small, medium, large, x-large, xxlarge, smaller, larger, pt, px, % circle, square, decimal, low-alpha upper-alpha, lowerroman, upper-roman, URL sub sup Definitions Underlines the text Line on the top of text Strikeout text Blinks text in N Removes decl. First char Caps

text-transform

text-indent line-height color background text-spacing text-align white-spacing

Specified margin N

Sets space between the text Aligns to window Removes wrapping Removes previous set

font-family font-style font-weight font-size

Exact Relative

list-style

Outside, inside

vertical-align

Page No. 30

Web Technologies

UNIT II JAVA SCRIPT Scripting languages are programming languages that are generally easy to learn, easy to use, excellent for small routine and applications, and developed to serve a particular purpose. For instance, Perl (Practical Extraction and Report Language) began its life as a scripting language written for the express purpose of extracting and manipulating data and writing reports. Scripting languages are usually interpreted rather than compiled. That means that a software routine, an interpreter, must translate a program's statement into machine code, code understandably by a particular type of computer, before executing them every time the program is run. Compiled languages, on the other hand, are translated into machine code and stored for later execution. Programs written interpreted languages must be translated into machine code every time they are run, they are typically slower than compiled programs. Being interpreted does have its advantages. One is platform independence. Because an interpreter performs the translation, you can write your program once and run it on a variety of platforms. In the case of JavaScript, the interpreter is built into Web Browsers. Browsers are available for a variety of platforms and operating systems. Another advantage is that scripting languages are often loosely typed and more forgiving then compiled languages. As a scripting language, JavaScript is easy to learn and easy to use. You can embed command directly into your HTML code and the browser will interpret and run them at the appropriate time. JavaScript is loosely typed. You don't have to declare the type of data that will be stored in available before you use it. Java Vs Java Script JavaScript and Java are alike in more than just name. However, there are significant differences between these two languages. As you learn to understand the differences, you will also understand how they can work together. Each has its place and neither does it all. Following Table provides a quick overview of the differences. JavaScript Interpreted by client Code integrated in HTML documents Loose typing of data types Dynamic binding Script limited to browser functions Works with HTML elements Access browser functionality objects Java Compiled by the author, run on client Applets distinct from HTML document Strong typing of data types Static binding Stand-alone applications Goes beyond HTML (for example, multimedia) and No access to browser functionality objects or
Page No. 31

Web Technologies

History: JavaScript was created by Brendan Eich of Netscape Communications and was first made available in 1995 as part of Netscape Navigator 2.0, the first JavaScript-enabled Web browser. Originally called LiveScript, JavaScript owes the Java part of its name to the popularity of Java, the cross-platform, Object-Oriented Programming language created by Sun Microsystems. Writing JavaScript JavaScript code is typically embedded in the HTML, to be interpreted and run by the client's browser. Here are some tips to remember when writing JavaScript commands. JavaScript code is case sensitive White space between words and tabs are ignored Line breaks are ignored except within a statement JavaScript statements end with a semi- colon ;

The SCRIPT Tag The <SCRIPT> tag alerts a browser that JavaScript code follows. It is typically embedded in the HTML. Script code can be written in script element of HTML <script>...</script> <SCRIPT language = "JavaScript"> statements </SCRIPT> SCRIPT Example <SCRIPT language = "JavaScript"> alert("Welcome to the script tag test page.") ; </SCRIPT> Attributes of script element are: TYPE: providing content type Ex: type=text/javascript LANGUAGE: Specifying the which scripting language that script is using default is JavaScript Ex: language=javascript SRC : A URL of externally linked script
Ex: SRC="filename.js"

Embedding JavaScript into a HTML-page JavaScript code is embedded directly into the HTML-page. In order to see how this works we are going to look at an easy example:
Page No. 32

Web Technologies

<html> <body> <br> This is a normal HTML document. <br> <script language="JavaScript"> document.write("This is JavaScript!") </script> <br> Back in HTML again. </body> </html> At the first glance this looks like a normal HTML-file. The only new thing is the part: <script language="JavaScript"> document.write("This is JavaScript!") </script> This is JavaScript. In order to see this script working save this code as a normal HTML-file and load it into your JavaScript-enabled browser. Here is the output generated by the file (if you are using a JavaScript browser you will see 3 lines of output):

There you see the use of document.write() - one of the most important commands in JavaScript programming. document.write() is used in order to write something to the actual document (in this case this is the HTML-document). So our little JavaScript program writes the text. This is JavaScript! to the HTML-document.
There are three ways to add JavaScript commands to your Web Pages. Inline Scripting (Embedding code Internal Scripting External Scripting (External file ) Page No. 33

Web Technologies

In Line Scripting <html> <head><title>Script Demo -1</title> </head> <body> <script language="javascript"> document.write("<H2>Welcome to Java Script</H2> "); </script></body></html> Internal Scripting <html> <head><title>Script Demo - 2</title> <script language="javascript"> document.write("<H2>Welcome to Java Script</H2> "); </script> </head><body></body> </html> External File You can use the SRC attribute of the <SCRIPT> tag to call JavaScript code from an external text file. This is useful if you have a lot of code or you want to run it from several pages, because any number of pages can call the same external JavaScript file. The text file itself contains no HTML tags. <SCRIPT SRC="filename.js"> </SCRIPT> <SCRIPT language = "JavaScript" SRC = "external.js"> </SCRIPT> Hiding Scripts within Comment Tags Only Netscape Navigator versions 2.0 and later recognize JavaScript. If a browser does not recognize javascript code, the whole code in displayed when you see the HTML document. To ensure that your JavaScript code is not displayed by old browsers, place Javascript inside comment fields. The markup to begin a comment field is <!-- while you close a comment field using //-->. Eg: <SCRIPT> <!-- Hide script contents from old browsers that does not javascript. Include JavaScript statements... // Finish hiding here. --> </SCRIPT>
Page No. 34

Web Technologies Variable Declaration Programmers use variables to store values. A variable can hold several types of data. In JavaScript you don't have to declare a variable's data type before using it. Any variable can hold any JavaScript data type, including: String data Numbers Boolean values (T/F) o To declare variables, use the keyword var and the variable name: var userName o To assign values to variables, add an equal sign and the value: var userName = "Smith" var price = 100 JavaScript Input/Output ALERT

Alert boxes are used to display some text information and have the visitor click on the OK button to continue on. This script is usually placed in the HEAD area of the code which makes the box appear before the actual page load. <script type="text/javascript"> alert ("Welcome to my friend"); </script> ALERT creates the actual ALERT box to appear. Anything placed within the double quotes will become the message that appears on the ALERT box. In this example a dialogue box will be displayed which will contain the message-Welcome my friend. The Javascript confirm function is very similar to the Javascript alert function. The following example shows how to make use of 'confirm' dialog box. This dialog box can be used for confirming something. The confirm box is different than the alert box in that it supplies the user with a choice, they can either press OK to confirm the popups message or they can press cancel and not agree to the popups request.This function returns a boolean value (true or false). If you press 'Ok', True is returned, if 'cancel' is pressed False is returned. After clicking OK or 'cancel', see the status bar for results. <script language="javascript"> var ans = confirm ("Are you having fun?") if (answer) alert ("Welcome to my friend"); </script>
Page No. 35 CONFIRM

Web Technologies

A PROMPT is used to actually gather a bit of information when a simple TRUE/FALSE is not enough. This will take some information from the visitor and you can use it in other applications. PROMPT creates the actual pop-up box with a text area for the visitor to enter information based on the text following the PROMPT command. The empty set of quotes in the second part of the PROMPT is to clear the PROMTP text box. You can enter any text within the quotes to have a default answer appear. <script type="text/javascript"> var answer = prompt ("please enter your name ?","") alert ("Hello there, " + answer) </script>

PROMPT

In the PROMPT example if we entered nothing then it will read null If we enter any name in place of null it will display user entered name value Functions With functions, you can give a name to a whole block of code, allowing you to reference it from anywhere in your program. JavaScript has built-in functions for several predefined operations. Here are three some functions. alert("message") confirm("message") prompt("message") User-Defined Functions With user-defined functions, you can name a block of code and call it when you need it. You define a function in the HEAD section of a web page. It is defined with the function keyword, followed by the function name and any arguments. function functionName(argument) { statements } <SCRIPT language = "JavaScript"> function showAlert() { alert("this is a user-defined function.") } </SCRIPT>
Page No. 36

Web Technologies

Built-In Objects Some of the built-in language objects of JavaScript offer more advanced operations such as: Math provides for math calculations Date provides date and time information String provides for string manipulation Objects JavaScript supports programming with objects. Objects are a way of organizing the variables. The different screen elements such as Web pages, forms, text boxes, images, and buttons are treated as objects. Properties and Methods Every object has its own properties and methods. Properties define the characteristics of an object. Examples: color, length, name, height, width Methods are the actions that the object can perform or that can be performed on the object. Examples: alert, confirm, write, open, close JavaScript uses dot notation to refer to an object and its associated properties and methods for instance, in dot notation we refer to the document object and its background property color we write document.bgColor We can also write directly to document using the document's write method document.write("Hello") Try It: Open a text editor or HTML editor and type the following code (docobj.html); <HTML> <HEAD> <TITLE> Script: using of write method </TITLE> </HEAD> <BODY bgcolor="red" text="black"> <SCRIPT language = "JavaScript" type="text/JavaScript"> document.bgColor="cyan"; document.write("Hello"); </SCRIPT> </BODY> </HTML> Save your document as a text file with an .html extension and open it in your browser, The result should look similar to this
Page No. 37

Web Technologies

You can even use JavaScript to write HTML. Modify the above script write the greeting as ventered heading. <SCRIPT language = "JavaScript" type="text/JavaScript"> document.bgcolor="cyan"; document.write("<CENTER><H1>Hello</H1></CENTER>"); </SCRIPT> Hear what it looks like:

Document Object The Document object represents the Web page that is loaded in the browser window, and the content displayed on that page, including text and form elements. Document Methods You can use the methods of the document object to work on a Wb page. Here are the most common document methods: write() - write a string to the Web page open() - opens a new document close() - closes the document Document Example Keep the "docobj.html" file open Put the cursor after the document.write("Hello"); and enter: document.write(Who is this!) document.write(How are you) Save the changes and Refresh the page You will notice that the results of all three strings are printed on one line and without any spaces between the results. You can avoid this by including some formatting in your "document.write" statement. Document Formatting Example Open "docobj.html" and View the Source Modify three document.write methods as specified: document.write("<H1>Hello</H1>") document.write("<H2>Who is this!</H2>") document.write("<B>How are you</B >") Save the changes and Refresh the page
Page No. 38

Web Technologies

Document Properties Use the properties of the document object to set the colors of the page, the title and display the date the document was last modified. JavaScript has about 150 defined color words you can use or you can provide the hexidecimal RGB codes. Here are the most common document properties: bgColor fgColor linkColor vlinkColor title lastModified Window Object The window object represents the browser window. You can use it to open a Web page in a new window and to set the attributes for the window. There are only two main window properties. They are: status - set the status bar message self - stores the name mof the current window Window Methods The window methods are mainly for opening and closing new windows. The following are the main window methods. They are:
open() close() focus() blur() moveBy() moveTo() resizeBy() resizeTo() scrollBy() scrollTo() print() alert() prompt() confirm()
Opens a new browser window Closes the current window Sets focus to the current window Removes focus from the current window Moves a window relative to its current position Moves a window to the specified position Resizes the window by the specified pixels Resizes the window to the specified width and height Scrolls the content by the specified number of pixels Scrolls the content to the specified coordinates Prints the content of the current window Displays an alert box with a message and an OK button Displays a dialog box that prompts the visitor for input Displays a dialog box with a message and an OK and a Cancel button

Window Attributes If the default new window does not suit your needs, you can specify different features of the window when you open it. The complete syntax of the "window.open" is as follow: window.open(URL, windowName, featureList)
Page No. 39

Web Technologies

By default, if you do not specify any features, then a window will have all of them. If you specify any one feature, then the window will have only those you set equal to 1. The following are the window attributes: toolbar menubar scrollbars resizeable status location directories
Sets or returns the name of a window Sets or returns the default text in the statusbar of a window Sets the text in the statusbar of a window Returns the number of frames (including iframes) in a window Returns the pixels the current document has been scrolled (horizontally) from the upper left corner of the window Returns the pixels the current document has been scrolled (vertically) from the pageYOffset upper left corner of the window screenX , screenLeft Returns the x coordinate of the window relative to the screen screenY, screenTop Returns the y coordinate of the window relative to the screen Returns the current window self Returns a reference to the window that created the window opener Returns the topmost browser window top Returns the parent window of the current window parent Returns a Boolean value indicating whether a window has been closed or not closed Returns an array of all the frames (including iframes) in the current window frames

name defaultStatus status length pageXOffset

Window Properties:

document history location navigator screen length back() forward() go()

Window Objects:

Returns the Document object for the window (See Document object) Returns the History object for the window (See History object) Returns the Location object for the window (See Location object) Returns the Navigator object for the window (See Navigator object) Returns the Screen object for the window (See Screen object) Returns the number of URLs in the history list Loads the previous URL in the history list Loads the next URL in the history list Loads a specific URL from the history list (..-1,1..)

History Object:

appName appVersion cookieEnabled platform userAgent javaEnabled()

Navigator Object Properties and method Returns the name of the browser Returns the version information of the browser Determines whether cookies are enabled in the browser Returns for which platform the browser is compiled Returns the user-agent header sent by the browser to the server Specifies whether or not the browser has Java enabled

Page No. 40

Web Technologies

The location-object Besides the window- and document-objects there is another important object: the location-object. This object represents the address of the loaded HTML-document. So if you loaded the page http://www.xyz.com/page.html then location.href is equal to this address. What is more important is that you can assign new values to location.
hash host hostname href pathname port protocol search assign() reload() replace()
Returns the anchor portion of a URL Returns the hostname and port of a URL Returns the hostname of a URL Returns the entire URL Returns the path name of a URL Returns the port number the server uses for a URL (for port 80 nothing returns) Returns the protocol of a URL Returns the query portion of a URL (returns after ?) Loads a new document Reloads the current document Replaces the current document with a new one

The Date-object JavaScript lets you use some predefined objects. We are going to have a look at the Date-object first. As the name implies this object lets you work with time and date. For example you can easily calculate how many days are left until next Festival. Or you can add the actual time to your HTML-document. So lets begin with an example which displays the actual time. First we have to create a new Date-object. For this purpose we are using the new operator. Look at this line of code: var doday; today= new Date(); This creates a new Date-object called today. If you do not specify a certain date and time when creating a new Date-object the actual date and time is used. This means after executing today= new Date() the new Date-object today represents the date and time of this specific moment. The Date-object offers some methods which can now be used with our object today. This is for example getHours(), setHours(), getMinutes(), setMinutes(), getMonth(), setMonth() and so on. In order to get another date and time we can use another constructor (this is the Date() method which is called through the new operator when constructing a new Date-object): today= new Date(1997, 0, 1, 17, 35, 23)

Page No. 41

Web Technologies

This will create a Date-object which represents the first of January 1997 at 17:35 and 23 seconds. So you specify the date and time like this: Date(year, month, day, hours, minutes, seconds) Please note that you have to use 0 for January - and not 1 as you might think. 1 stands for February and so on. Now we will write a script which outputs the actual date and time. The result will look like this: Time: 17:53 Date: 4/3/2010 The code looks like this: <script language="JavaScript"> now= new Date(); document.write("Time: " + now.getHours() + ":" + now.getMinutes() + "<br>"); document.write("Date: " + (now.getMonth() + 1) + "/" + now.getDate() + "/" + (1900 + now.getYear())); </script> The Array-object Arrays are very important. Just think of an example where you want to store 100 different names. How could you do this with JavaScript? Well, you could define 100 variables and assign the different names to them. This is quite complicated. Arrays can be seen as many variables bundled together. You can access them through one name and a number. Lets say out array is called names. Then we can access the first name through myArray[0]. The second name is called myArray[1] and so on. You can create a new array through myArray= new Array(). Now you can assign values to this array: myArray[0]= 17; myArray[1]= "Stefan"; myArray[2]= "Koch"; JavaScript arrays are really flexible. You do not have to bother about the size of the array its size is being set dynamically. The Math-object If you need to do mathematical calculations you will find some methods in the Math object which might help you further. There is for example a sine-method sin(). You will find a complete reference in the Netscape documentation. I want to demonstrate the random() method. If you have read the first version of this tutorial you know that there have been some problems with the random() method. We wrote a function
Page No. 42

Web Technologies

which let us create random numbers. We dont need that anymore as the random() method now works on all platforms. If you call Math.random() you will receive a random number between 0 and 1. Here is one pos sible output of document.write(Math.random()). DOM

Web documents are made available to Client-Side JavaScript via the Document Object Model(DOM). The DOM illustration represents the DOM common to all major browsers. The items contained in a Web document become objects in the browser's memory as the browser loads and interprets the HTML code that defines them. Notice that the DOM is arranged in a hierarchical way with window as the highest-level object.

<HTML> <HEAD> </HEAD> <BODY > </BODY> </HTML>


Page No. 43

Web Technologies
DOM (Document Object.)

Returns an array of all the anchors in the document anchors[] Returns an array of all the forms in the document forms[] Returns an array of all the images in the document images[] Returns an array of all the links in the document links[] Sets or returns the title of the document ti tl e Returns the full URL of the document URL Closes the output stream previously opened with document.open() close() Accesses the first element with the specified id getElementById() Accesses all elements with a specified name getElementsByName() getElementsByTagName( Accesses all elements with a specified tagname ) Opens an output stream to collect the output from document.write() or open()

write() writeln()

document.writeln() Writes HTML expressions or JavaScript code to a document Same as write(), but adds a newline character after each statement

Events The objects in a Web pages are organized in a hierarchy. Events and event handlers are very important for JavaScript programming. Events are mostly caused by user actions. If the user clicks on a button a Click-event occurs. If the mousepointer moves across a link a MouseOver-event occurs. There are several different events. All objects have properties and methods. In addition, some objects also have "events". Events are things that happen, usually user actions, that are associated with an object. The "event handler" is a command that is used to specify actions in response to an event. Below are some of the most common events: onLoad - occurs when a page loads in a browser onUnload - occurs just before the user exits a page onMouseOver - occurs when you point to an object onMouseOut - occurs when you point away from an object onSubmit - occurs when you submit a form onClick - occurs when an object is clicked Events and Objects Events are things that happen, actions, that are associated with an object. Below are some common events and the object they are associaated with: Event Object onLoad Body onUnload Body onMouseOver Link, Button onMouseOut Link, Button onSubmit Form onClick Button, Checkbox, Submit, Reset, Link
Page No. 44

Web Technologies

We want our JavaScript program to react to certain events. This can be done with the help of event-handlers. A button might create a popup window when clicked. This means the window should pop up as a reaction to a Click-event. The event-handler we need to use is called onClick. This tells the computer what to do if this event occurs. The following code shows an easy example of the event-handler onClick: <form> <input type="button" value="Click me" onClick="alert(Yo)"> </form> There are a few new things in this code - so lets take it step by step. You can see that we create a form with a button. The new part is onClick="alert(Yo)" inside the <input> tag. If a Click-event occurs the computer shall execute alert(Yo). This is JavaScript-code alert() letsyou create popup windows. Inside the brackets you have to specify a string. In our case this is Yo. This is the text which shall be shown in the popup window. So our script creates a window with the contents Yo when the user clicks on the button. One thing might be a little bit confusing: In the document.write() command we used double quotes " and in combination with alert() we use only single quotes - why? Basically you can use both. But in the last example we wrote onClick="alert(Yo)" you can see that we used both double and single quotes. If we wrote onClick="alert("Yo")" the computer would get confused as it isnt clear which part belongs to the onClick event-handler and which not. So you have to alternate with the quotes in this case. It doesnt matter in which order you use the quotes first double quotes and then single quotes or vice versa. This means you can also write onClick=alert("Yo"). JavaScript hierarchy JavaScript organizes all elements on a web-page in a hierarchy. Every element is seen as a object. Each object can have certain properties and methods. With the help of JavaScript you can easily manipulate the objects. For this it is very important to understand the hierarchy of HTMLobjects. We have two images, one link and a form with two text fields and a button. From JavaScripts point of view the browser window is a window-object. This windowobject contains certain elements like the statusbar. Inside a window we can load a HTML-document. This page is a document-object. This means the document-object represents the HTML-document which is loaded at the moment. Properties of the document-object are for example the background color of the page. But what is more important is that all HTML-objects are properties of the document-object. A HTMLobject is for example a link, or a form. You will quickly understand how this works with the help of an example.

Page No. 45

Web Technologies

The following image illustrates the hierachy created by our example HTML-page:

We want to be able to get information about the different objects and manipulate them. For this we must know how to access the different objects. You can see the name of the objects in the hierarchy. If you now want to know how to address the first image on the HTML-page you have to look at the hierarchy. You have to start from the top. The first object is called document. The first image the page is represented through images[0]. This means that we can access this object through JavaScript with document.images[0]. If you for example want to know what the user entered into the first form element you must first think about how to access this object. Again we start from the top of our hierarchy. Follow the path to the object
Page No. 46

Web Technologies

called elements[0] - put all the names of the object you pass together. This means you can access the first textelement through: document.forms[0].elements[0] But how can we now get to know the entered text? In order to find out which properties and methods an object offers you have to look into a JavaScript reference. There you will see that a textelement has got the property value. This is the text entered into the textelement. Now we can read out the value with this line of code: name= document.forms[0].elements[0].value; Validating form input Forms are widely used on the Internet. The form input is often being sent back to the server or via mail to a certain e-mail account. But how can you be certain that a valid input was done by the user? With the help of JavaScript the form input can easily be checked before sending it over the Internet. First of all we want to create a simple script. The HTML-page shall contain two textelements. The user has to write his name into the first and an e-mail address into the second element. If the user has entered his name (for example Kanth) into the first text-field the script creates a popup window with the text Hi Kanth!. Concerning the first input element you will receive an error message when nothing is entered. Any input is seen as valid input. Of course, this does not prevent the user from entering any wrong name. The browser even accepts numbers. So if you enter '17' you will get 'Hi 17!'. So this might not be a good check. The second form is a little bit more sophisticated. Try to enter a simple string - your name for example. It won't work (unless you have a @ in your name...). The criteria for accepting the input as a valid e-mail address is the @. A single @ will do it but this is certainly not very meaningful. Every Internet e-mail address contains a @ so it seems appropriate to check for a @ here. <html> <head> <script language="JavaScript"> <!-- Hide function test1(form) { if (form.text1.value == "") alert("Please enter a string!") else { alert("Hi "+form.text1.value+"! Form input ok!"); } } function test2(form) { if (form.text2.value == "" || form.text2.value.indexOf(@, 0) == -1)
Page No. 47

Web Technologies

} </script> </head> <body> <form name="first"> Enter your name:<br> <input type="text" name="text1"> <input type="button" name="b1" value="Test Input" onClick="test1(this.form)"> <P > Enter your e-mail address:<br> <input type="text" name="text2"> <input type="button" name="b2" value="Test Input" onClick="test2(this.form)"> </body> </html> Two buttons, call the functions test1(...) or test2(...) depending on which button is pressed. We pass this.form to the functions in order to be able to address the right elements in the functions later on. The function test1(form) tests if the string is empty. This is done via if(form.text1.value = = "");. form is the variable which receives the this.form value in the function call. We can get the value of the input element through using value in combination with form.text1. In order to look if the string is empty we compare it with "". If the input string equals "" then no input was done. The user will get an error message. If something is entered the user will get an ok. Sometimes you want to restrict the form input to certain characters or numbers. Just think of a telephone number the input should only contain digits (we assume that the telephone number does not contain any characters). We could check if the input is a number. But most people use different symbols in their telephone number - for example: 01234-56789, 01234/56789 or 01234 56789 (with a space in between). The user should not be forced to enter the telephone number without these symbols. So we have to extend our script to check for digits and some symbols. This is demonstrated in the next example which is taken. <html> <head> <script language="JavaScript">function check(input) { var ok = true; for (var i = 0; i < input.length; i++) { var chr = input.charAt(i); var found = false; for (var j = 1; j < check.length; j++) { if (chr == check[j]) found = true;
Page No. 48

alert("No valid e-mail address!"); else alert("OK!");

Web Technologies

} function test(input) { if (!check(input, "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "/", "-", " ")) { alert("Input not ok."); } else alert("Input ok!"); } </script> </head> <body> <form> Telephone: <input type="text" name="telephone" value=""> <input type="button" value="Check" onClick="test(this.form.telephone.value)"> </form> </body> </html> The function test() specifies which characters are valid.

} return ok;

} if (!found) ok = false;

Page No. 49

SICET Web Technologies

Prepared By: A. Laxmi Kanth

UNIT - III
What is XML? The essence of XML is in its name: Extensible Markup Language. Extensible XML is extensible. It lets you define your own tags, the order in which they occur, and how they should be processed or displayed. Another way to think about extensibility is to consider that XML allows all of us to extend our notion of what a document is. Markup The most recognizable feature of XML is its tags, or elements (to be more accurate). In fact, the elements you'll create in XML will be very similar to the elements you've already been creating in your HTML documents. However, XML allows you to define your own set of tags. Language XML is a language that's very similar to HTML. It's much more flexible than HTML because it allows you to create your own custom tags. However, it's important to realize that XML is not just a language. XML is a meta-language: a language that allows us to create or define other languages. For example, with XML we can create other languages, such as RSS, MathML (a mathematical markup language), and even tools like XSLT. Consider the following

<html <head> <title>ABC Products</title> </head> <body> <h1>ABC Products</h1> <h2>Product One</h2> <p>Product One is an exciting new widget that will simplify your life.</p> <p><b>Cost: $19.95</b></p> <h3>Product Two</h3> <p><i>Cost: $29.95</i></p> <p>Product Two is an exciting new widget that will make you Jump up and down</p> <p><b>Shipping: $5.95</b></p> </body> </html>
For example, a human can probably deduce that the <h2> tag in the above document has been used to tag a product name within a product listing. Furthermore, a human might be able to guess that the first paragraph after an <h2> holds the description, and that the next two paragraphs contain price and shipping information, in bold. However, even a cursory glance at the rest of the document reveals some very human errors. For example, the last product name is encapsulated in <h3> tags, not <h2> tags. This last Page No. 50

SICET Web Technologies

Prepared By: A. Laxmi Kanth

product listing also displays a price before the description, and the price is italicized instead of appearing in bold. A computer program (and even some humans) that tried to decipher this document wouldn't be able to make the kinds of semantic leaps required to make sense of it. The computer would be able only to render the document to a browser with the styles associated with each tag. HTML is chiefly a set of instructions for rendering documents inside a Web browser; it's not a method of structuring documents to bring out their meaning. If the above document were created in XML, it might look a little like First

<?xml version="1.0"?> <productListing title="ABC Products"> <product> <name>Product One</name> <description>Product One is an exciting new widget that will simplify your life.</description> <cost>$19.95</cost> <shipping>$2.95</shipping> </product> <product> <name>Product Two</name> <description>Product Two is an exciting new widget that will make you Jump up and down</description <cost>$29.95</cost> <shipping>$5.95</shipping> </product> </productListing>
Notice that this new document contains absolutely no information about display. What does a <product> tag look like in a browser? Beats mewe haven't defined that yet. Later on, we'll see how you can use technologies like CSS and XSLT to transform your XML into any format you like. Essentially, XML allows you to separate information from presentationjust one of its many powerful abilities. When we concentrate on a document's structure, as we've done here, we are better able to ensure that our information is correct. In theory, we should be able to look at any XML document and understand instantly what's going on. In the example above, we know that a product listing contains products, and that each product has a name, a description, a price, and a shipping cost. You could say, rightly, that each XML document is self-describing, and is readable by both humans and software. Now, everyone makes mistakes, and XML programmers are no exception. Imagine that you start to share your XML documents with another developer or company, and, somewhere along the line, someone places a product's description after its price. Normally, this wouldn't be a big deal, but perhaps your Web application requires that the description appears after the product name every time.

Example:

Page No. 51

SICET Web Technologies

Prepared By: A. Laxmi Kanth

To ensure that everyone plays by the rules, you need a DTD (a document type definition), or schema. Basically, a DTD provides instructions about the structure of your particular XML document. It's a lot like a rule book that states which tags are legal, and where. Once you have a DTD in place, anyone who creates product listings for your application will have to follow the rules. We'll get into DTDs a little later. For now, though, let's continue with the basics. A Closer Look at the XML Example The simplest XML elements contain an opening tag, a closing tag, and some content. The opening tag begins with a left angle bracket (<), followed by an element name that contains letters and numbers (but no spaces), and finishes with a right angle bracket (>). In XML, content is usually parsed character data. It could consist of plain text, other XML elements, and more exotic things like XML entities, comments, and processing instructions (all of which we'll see later). Following the content is the closing tag, which exhibits the same spelling and capitalization as your opening tag, but with one tiny change: a / appears right before the element name. Here are a few examples of valid XML elements:

<myElement>some content here</myElement> <elements> <myelement>one</myelement> <myelement>two</myelement> </elements>


Elements, Tags, or Nodes? XML elements, XML tags, and XML nodes, these terms are interchangeable, but if you want to get technical (and who'd want to do that in a technical book?) each has a very precise meaning: An element consists of an opening tag, its attributes, any content, and a closing tag. A tageither opening or closingis used to mark the start or end of an element. A node is a part of the hierarchical structure that makes up an XML document. "Node" is a generic term that applies to any type of XML document object, including elements, attributes, comments, processing instructions, and plain text. If you're used to working with HTML, you've probably created many documents that are missing end tags, use different capitalization in opening and closing tags, and contain improperly nested tags. You won't be able to get away with any of that in XML! In this language, the <myElement> tag is different from the <MYELEMENT> tag, and both are different from the <myELEMENT> tag. If your opening tag is <myELEMENT> and your closing tag is </Myelement>, your document won't be valid. If you use attributes on any elements, then attribute values must be single- or double-quoted. No longer can you get by with bare attribute values like you did in HTML! Let's see an example. The following is okay in HTML:

<h1 class=topHeader>
Page No. 52

SICET Web Technologies

Prepared By: A. Laxmi Kanth

In XML, you'd have to put quotes (either single or double) around the attribute value, like this:

<h1 class="topHeader">
Also, if you nest your elements improperly (i.e. close an element before closing another element that is inside it), your document won't be valid. (I know I keep mentioning validitywe'll talk about it in detail soon!) For example, Web browsers don't generally complain about the following:

<b>Some text that is bolded, some that is <i>italicized</b></i>.


In XML, this improper nesting of elements would cause the program reading the document to raise an error. The rule states that each XML document must contain a single root element in which all the document's other elements are contained. Attributes Did you notice the <productListing> opening tag in our example? Inside the tag, following the element name, was the data title="ABC Products". This is called an attribute. You can think of attributes as adjectivesthey provide additional information about the element that may not make any sense as content. If you've worked with HTML, you're familiar with such attributes as the src (file source) on the <img> tag. What information should be contained in an attribute? What should appear between the tags of an element? This is a subject of much debate, but don't worry, there really are no wrong answers here. Remember: you're the one defining your own language. Some developers (including me!) apply this rule of thumb: use attributes to store data that doesn't necessarily need to be displayed to a user of the information. Another common rule of thumb is to consider the length of the data. Potentially large data should be placed inside a tag; shorter data can be placed in an attribute. Let's examine this issue a little more closely. Let's say that you wanted to create an XML document to keep track of your DVD collection. Here's a short snippet of the code you might use:

<dvdCollection> <dvd> <id>1</id> <title>Raiders of the Lost Ark</title> <release-year>1981</release-year> <director>Steven Spielberg</director> <actors> <actor>Harrison Ford</actor> <actor>Karen Allen</actor> <actor>John Rhys-Davies</actor> </actors> </dvd> . </dvdCollection>

Page No. 53

SICET Web Technologies

Prepared By: A. Laxmi Kanth

It's unlikely that anyone who reads this document would need to know the ID of any of the DVDs in your collection. So, we could safely store the ID as an attribute of the <dvd> element instead, like this: In other parts of our DVD listing, the information seems a little bare. For instance, we're only displaying an actor's name between the <actor> tagswe could include much more information here. One way to do so is with the addition of attributes:

<dvd id="1">

<actor type="superstar" gender="male" age="50">Harrison Ford </actor>


In this case, though, I'd probably revert to our rule of thumbmost users would probably want to know at least some of this information. So, let's convert some of these attributes to elements:

<actor type="superstar"> <name>Harrison Ford</name> <gender>male</gender> <age>50</age> </actor>


Empty-Element Tags Some XML elements are said to be emptythey contain no content whatsoever. Familiar examples are the img and br elements in HTML. In the case of img, for example, all the element's information is contained in its tag's attributes. The <br> tag, on the other hand, does not normally contain any attributesit just signifies a line break. Remember that in XML all opening tags must be matched by a closing tag. For empty elements, you can use a single empty-element tag to replace this:

<myEmptyElement></myEmptyElement> <myEmptyElement/>
The / at the end of this tag basically tells the parser that the element starts and ends right here. It's an efficient shorthand method that you can use to mark up empty elements quickly. The XML Declaration The line right at the top of our example is called the XML declaration: with this:

<?xml version="1.0"?>
It's not strictly necessary to include this line, but it's the best way to make sure that any device that reads the document will know that it's an XML document, and to which version of XML it conforms.

Page No. 54

SICET Web Technologies Entities

Prepared By: A. Laxmi Kanth

I mentioned entities earlier. An entity is a handy construct that, at its simplest, allows you to define special characters for insertion into your documents. If you've worked with HTML, you know that the &lt; entity inserts a literal < character into a document. You can't use the actual character because it would be treated as the start of a tag, so you replace it with the appropriate entity instead. The logical structure of an XML document.

Because what we have is a tree, we should be able to travel up and down it, and from side to side, with relative ease. Save the First Example XML markup into a file and name it myFirstXML.xml. Viewing Raw XML in Internet Explorer If you have Internet Explorer 5 or higher installed on your machine, you can view your newly-created XML file. Internet Explorer simply displays XML files as a series of indented nodes.

Page No. 55

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Notice the little minus signs next to some of the XML nodes? A minus sign in front of a node indicates that the node contains other nodes. If you click the minus sign, Internet Explorer will collapse all the child nodes belonging to that node, as shown below.

The little plus sign next to the first product node indicates that the node has children. Clicking on the plus sign will expand any nodes under that particular node. In this way, you can easily display the parts of the document on which you want to focus. Now, open your XML document in any text editing tool and scroll down to the cost node of the second product. The line we're interested in should read:

<cost>$29.95</cost> Capitalize the "c" on the opening tag, so that the line reads like this:
Save your work and reload Internet Explorer. You should see an error message that looks like the one pictured in Figure 1.4, "Error message displaying in Internet Explorer.". Error message displaying in Internet Explorer.

<Cost>$29.95</cost>

Page No. 56

SICET Web Technologies

Prepared By: A. Laxmi Kanth

As you can see, Internet Explorer provides a rather verbose explanation of the error it ran into: the end tag, </cost>, does not match the start tag, <Cost>. Furthermore, it provides a nice visual of the offending line, a little arrow pointing to the spot at which the parser thinks the problem arose.

<Cost>$29.95</cost> --------------^
Even though the problem is really with the start tag, the arrow points to the end tag. Because Internet Explorer uses a non-validating parser by default (remember, this means it only cares about well-formedness rules), it runs into problems at the end tag. You now have to backtrack to find out why that particular end tag caused such a problem. Once you get the hang of this debugging method, you'll find it a great help in tracking down problems. Let's introduce a slightly more complex problem. Open your XML document in an editor once more, and fix the problem we introduced above. Then, go to the second-last line of the document (it should read </product>) and add a <product> tag in front of it. Save your work and reload your browser. You should see an error message look like "Debugging a more complex error.". Debugging a more complex error.

At first glance, this error message seems a bit more obscure than the previous one. For starters, this message seems to indicate a problem with the </productListing> end tag. However, look closely and what do you see? It says that the </productListing> end tag does not match the <product> start tag. That's exactly what's wrong! Someone introduced a <product> start tag and didn't close it properly. I'm including this example because bad nesting is one of the most common errors introduced to XML documents. This kind of error can be subtle and hard to find, especially if you're doing a lot of editing, or if your document is complex or long.

Page No. 57

SICET Web Technologies Using CSS to Display XML In a Browser

Prepared By: A. Laxmi Kanth

The most powerful tools available for displaying XML in a browser are XSLT and Cascading Style Sheets (CSS). Because XSLT can be quite a tricky undertaking for newbies, I've decided to let you practice with CSS first! The first step in working with CSS is to create a basic XML file:

<?xml version="1.0"?> <letter> <to>Mom</to> <from>Tom</from> <message>Happy Mother's Day</message> </letter>


As XML documents go, this one could be made a lot simpler, but there's no point in making things too simple. This document contains a root element (letter) that contains three other elements (to, from, and message), each of which contains text. Now, we need to add a style sheet declaration that will point to the CSS document we'll create. To associate a CSS style sheet with an XML file, use the <?xml-stylesheet?>directive: Example: letter-css.xml Finally, we write our CSS file, making sure that we provide a style for each element in our XML file: Example: letter.css

Example : letter.xml

<?xml-stylesheet type="text/css" href="letter.css"?>

When you display your XML document, you should see something similar to Figure 2.1, "Viewing the CSS results in Internet Explorer.".

letter { display: block; margin: 10px; padding: 5px; width: 300px; height: 100px; border: 1px solid #00000; overflow: auto; background-color: #cccccc; font: 12px Arial; } to, from { display: block; font-weight: bold; } message { display: block; font: 11px Arial; }

Page No. 58

SICET Web Technologies Viewing the CSS results in Internet Explorer.

Prepared By: A. Laxmi Kanth

Elements vs. Attributes <person> <slno>female</slno> <firstname>Anna</firstname> <lastname>Smith</lastname> </student> <student slno="1"> <firstname>Anna</firstname> <lastname>Smith</lastname> </student>

attributes can not contain multiple values (elements can) attributes are not expandable (for future changes) attributes can not describe structures (like child elements can) attributes are more difficult to manipulate by program code attribute values are not easy to test against a DTD

"Well Formed" XML documents A "Well Formed" XML document is a document that conforms to the XML syntax rules

XML documents must have a root element XML elements must have a closing tag XML tags are case sensitive XML elements must be properly nested XML attribute values must be quoted

Page No. 59

SICET Web Technologies

Prepared By: A. Laxmi Kanth

"Valid" XML documents A "Valid" XML document is a "Well Formed" XML document which conforms to the rules of a Document Type Definition (DTD). XML DTD The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements. A DTD can be declared inline in your XML document, or as an external reference. NOTICE To: B.Tech IV CSE - A From: CR Message: Don't forget your seminar presentations will be on 29 th August (Saturday) <?xml version="1.0"> <note> <to> B.Tech IV CSE - A </to> <from> CR </from> <heading>Remainder</heading> <Message> Don't forget your seminar presentations will be on 29 th August (Saty)! </Message> </note> <!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT Message (#PCDATA)> ]>
External DTDs The DTD example we saw at the start of this chapter appeared within the DOCTYPE declaration at the top of the XML document. This is okay for experimentation purposes, but with many projects, you'll likely have dozensor even hundredsof files that must conform to the same DTD. In these cases, it's much smarter to put the DTD in a separate file, then reference it from your XML documents. An external DTD is usually a file with a file extension of .dtdfor example, letter.dtd. This external DTD contains the same notational rules set forth for an internal DTD. To reference this external DTD, you need to add two things to your XML document. First, you must edit the XML declaration to include the attribute standalone="no":

<?xml version="1.0" standalone="no"?>


Page No. 60

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Add a DOCTYPE declaration that points to the external DTD, like this:

<!DOCTYPE letter SYSTEM "letter.dtd">


This will search for the letter.dtd file in the same directory as the XML file. If the DTD lives on a different server, you might point to PUBLIC instead SYSTEM

<!DOCTYPE letter PUBLIC "http://www.example.com/xml/dtd/letter.dtd"> This is the same XML document with an external DTD: (Open it in IE5, and select view source) <?xml version="1.0"?> <!DOCTYPE note SYSTEM "note.dtd"> <note> <to> B.Tech IV CSE - A </to> <from> CR </from> <heading>Remainder</heading> <Message> Don't forget your seminar presentations will be on 29 th August (Saty)! </Message> </note> This is a copy of the file "note.dtd" containing the Document Type Definition: <?xml version="1.0"?> <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT Message (#PCDATA)> Element contains elements, pcdata, cdata or empty. DTD Elements Creating a DTD is quite straight forward. It's really just a matter of defining your elements, attributes, and/or entities. Over the next few lessons, I'll explain how to define your elements, attributes, and entities. To define an element in your DTD, you use the <!ELEMENT> declaration. The actual contents of your <!ELEMENT> declaration will depend on the syntax rules you need to apply to your element. Basic Syntax The <!ELEMENT> declaration has the following syntax: <!ELEMENT element_name content_model> Here, element_name is the name of the element you're defining. The content model could indicate a specific rule, data or another element. If it specifies a rule, it will be set to either ANY or EMPTY. If specifies data or another element, the data type/element name needs to be surrounded by brackets (i.e. (tutorial) or (#PCDATA)).
Page No. 61

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Plain Text If an element should contain plain text, you define the element using #PCDATA. PCDATA stands for Parsed Character Data and is the way you specify non-markup text in your DTDs. Using this example - <name>XML Tutorial</name> - the "XML Tutorial" part is the PCDATA. The other part consists of markup. Syntax:<!ELEMENT element_name (#PCDATA)> Example:<!ELEMENT name (#PCDATA)> The above line in your DTD allows the "name" element to contain non-markup data in your XML document: <name>XML Tutorial</name> Unrestricted Elements If it doesn't matter what your element contains, you can create an element using the content_model of ANY. Note that doing this removes all syntax checking, so you should avoid using this if possible. You're better off defining a specific content model. Syntax:<!ELEMENT element_name ANY> Example:<!ELEMENT tutorials ANY>
Empty Elements You might remember that an empty element is one without a closing tag. For example, in XHTML, the <br /> and <img /> tags are empty elements. Here's how you define an empty element: Syntax:<!ELEMENT element_name EMPTY> Example:<!ELEMENT header EMPTY> The above line in your DTD defines the following empty element for your XML document: <header /> Child Elements You can specify that an element must contain another element, by providing the name of the element it must contain. Here's how you do that: Syntax:<!ELEMENT element_name (child_element_name)> Example:<!ELEMENT tutorials (tutorial)> The above line in your DTD allows the "tutorials" element to contain one instance of the "tutorial" element in your XML document: <tutorials> <tutorial></tutorial> </tutorials> Page No. 62

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Multiple Child Elements (Sequences) You can also provide a comma separated list of elements if it needs to contain more than one element. This is referred to as a "sequence". The XML document must contain the tags in the same order that they're specified in the sequence. Syntax:<!ELEMENT element_name (child_element_name, child_element_name,...)> Example:<!ELEMENT tutorial (name, url)> The above line in your DTD allows the "tutorial" element to contain one instance of the "name" element and one instance of the "url" element in your XML document: <tutorials> <tutorial> <name></name> <url></url> </tutorial> </tutorials> DTD Element Operators One of the examples in the previous lesson demonstrated how to specify that an element ("tutorials") must contain one instance of another element ("tutorial"). This is fine if there only needs one instance of "tutorial", but what if we didn't want a limit. What if the "tutorials" element should be able to contain any number of "tutorial" instances? Fortunately we can do that using DTD operators. Here's a list of operators/syntax rules we can use when defining child elements: Operator Syntax Description + a+ One or more occurences of a * a* Zero or more occurences of a ? a? Either a or nothing , a, b a followed by b | a|b a followed by b () (expression) An expression surrounded by parentheses is treated as a unit and could have any one of the following suffixes ?, *, or +. Examples of usage follow. Zero or More To allow zero or more of the same child element, use an asterisk (*): Syntax:<!ELEMENT element_name (child_element_name*)> Example:<!ELEMENT tutorials (tutorial*)> One or More To allow one or more of the same child element, use a plus sign (+): Syntax:<!ELEMENT element_name (child_element_name+)> Example:<!ELEMENT tutorials (tutorial+)> Zero or One To allow either zero or one of the same child element, use a question mark (?): Syntax:<!ELEMENT element_name (child_element_name?)> Example:<!ELEMENT tutorials (tutorial?)> Page No. 63

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Choices You can define a choice between one or another element by using the pipe (|) operator. For example, if the "tutorial" element requires a child called either "name", "title", or "subject" (but only one of these), you can do the following: Syntax:<!ELEMENT element_name (choice_1 | choice_2 | choice_3)> Example:<!ELEMENT tutorial (name | title | subject)> Mixed Content You can use the pipe (|) operator to specify that an element can contain both PCDATA and other elements: Syntax:<!ELEMENT element_name (#PCDATA | child_element_name)> Example:<!ELEMENT tutorial (#PCDATA | name | title | subject)*> DTD Operators with Sequences You can apply any of the DTD operators to a sequence: Syntax:<!ELEMENT element_name (child_element_name dtd_operator, child_element_name dtd_operator,...)> Example:<!ELEMENT tutorial (name+, url?)> The above example allows the "tutorial" element to contain one or more instance of the "name" element, and zero or one instance of the "url" element. Subsequences You can use parentheses to create a subsequence (i.e. a sequence within a sequence). This enables you to apply DTD operators to a subsequence: Syntax:<!ELEMENT element_name ((sequence) dtd_operator sequence)> Example:<!ELEMENT tutorial ((author,rating?)+ name, url*)> The above example specifies that the "tutorial" element can contain one or more "author" elements, with each occurence having an optional "rating" element. DTD Attributes Just as you need to define all elements in your DTD, you also need to define any attributes they use. You use the <!ATTLIST> declaration to define attributes in your DTD. Syntax You use a single <!ATTLIST> declaration to declare all attributes for a given element. In other words, for each element (that contains attributes), you only need one <!ATTLIST> declaration. The <!ATTLIST> declaration has the following syntax: <!ATTLIST element_name attribute_name TYPE DEFAULT_VALUE ...> Here, element_name refers to the element that you're defining attributes for, attribute_name is the name of the attribute that you're declaring, TYPE is the attribute type, and DEFAULT_VALUE is it's default value. Example: <!ATTLIST tutorial published CDATA "No"> Page No. 64

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Here, we are defining an attribute called "published" for the "tutorial" element. The attribute's type is CDATA and it's default value is "No". Default Values The attribute TYPE field can be set to one of the following values: Value Description value A simple text value, enclosed in quotes. #IMPLIED Specifies that there is no default value for this attribute, and that the attribute is optional. #REQUIRED There is no default value for this attribute, but a a value must be assigned. #FIXED value The #FIXED part specifies that the value must be the value provided. The value part represents the actual value. Examples of these default values follow. Value You can provide an actual value to be the default value by placing it in quotes. Syntax:<!ATTLIST element_name attribute_name CDATA "default_value"> Example:<!ATTLIST tutorial published CDATA "No"> #REQUIRED The #REQUIRED keyword specifies that you won't be providing a default value, but that you require that anyone using this DTD does provide one. Syntax: <!ATTLIST element_name attribute_name CDATA #REQUIRED> Example: <!ATTLIST tutorial published CDATA #REQUIRED> #IMPLIED The #IMPLIED keyword specifies that you won't be providing a default value, and that the attribute is optional for users of this DTD. Syntax: <!ATTLIST element_name attribute_name CDATA #IMPLIED> Example: <!ATTLIST tutorial rating CDATA #IMPLIED> #FIXED The #FIXED keyword specifies that you will provide value, and that's the only value that can be used by users of this DTD. Syntax:<!ATTLIST element_name attribute_name CDATA #FIXED "value"> Example:<!ATTLIST tutorial language CDATA #FIXED "EN"> DTD Attribute Types So far, all our examples for declaring attributes have used the CDATA attribute type. CDATA is probably the most common attribute type as it allows for plain text to be used for the attribute's value. There may however, be cases where you need to use a different attribute type. When setting attributes for your elements, the attribute TYPE field can be set to one of the following values: Page No. 65

SICET Web Technologies

Prepared By: A. Laxmi Kanth

(Clicking on each type leads to a more detailed explanation of that type) Type Description CDATA Character Data (text that doesn't contain markup) ENTITY The name of an entity (which must be declared in the DTD) ENTITIES A list of entity names, separated by whitespaces. (All entities must be declared in the DTD) Enumerated A list of values. The value of the attribute must be one from this list. ID A unique ID or name. Must be a valid XML name. IDREF Represents the value of an ID attribute of another element. IDREFS Represents multiple IDs of elements, separated by whitespace. NMTOKEN A valid XML name. NMTOKENS A list of valid XML names, separated by whitespace. NOTATION A notation name (which must be declared in the DTD). DTD General Entities You may remember the lesson on creating entities. The entity we created in that lesson is known as a General Entity Reference. A general entity reference is used in the target XML document/s. This lesson refreshes our memory on how to declare a general entity. The following lesson introduces another type of entity; the parameter entity. Syntax:The <!ENTITY> declaration for general entities has the following syntax: <!ENTITY name definition> You can also declare external general entities. This enables you to use an entity from a remote file. You declare external general entities using the following syntax: Private:<!ENTITY name SYSTEM uri> Public:<!ENTITY name PUBLIC FPI uri> Example<!ENTITY author "Homer Flinstone"> After declaring the entity named "author", we can now use it in our XML document: <books> <book> <name>Life as a cartoon character</name> <author>&author;</author> </book> </book> 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. Tags inside the text will be treated as markup and entities will be expanded. CDATA CDATA also 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. Page No. 66

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Elements with children (sequences) Elements with one or more children are defined with the name of the children elements inside the parentheses: <!ELEMENT element-name (child-element-name)> or <!ELEMENT element-name (child-element-name,child-element-name,.....)> example: <!ELEMENT note (to,from,heading,body)> Declaring only one occurrence of the same element <!ELEMENT element-name (child-name)> example <!ELEMENT note (message)> Declaring minimum one occurrence of the same element <!ELEMENT element-name (child-name+)> example <!ELEMENT note (message+)>The + sign in the example above declares that the child element message must occur one or more times inside the note element. Declaring zero or more occurrences of the same element <!ELEMENT element-name (child-name*)> example <!ELEMENT note (message*)>The * sign in the example above declares that the child element message can occur zero or more times inside the note element. Declaring zero or one occurrences of the same element <!ELEMENT element-name (child-name?)> example <!ELEMENT note (message?)>The ? sign in the example above declares that the child element message can occur zero or one times inside the note element. Declaring mixed content <!ELEMENT note (to+,from,header,message*,#PCDATA)> The example above declares that the element note must contain at least one to child element, exactly one from child element, exactly one header, zero or more message, and some other parsed character data as well. Puh! Declaring Attributes In the DTD, XML element attributes are declared with an ATTLIST declaration. An attribute declaration has the following syntax: <!ATTLIST element-name attribute-name attribute-type default-value> Value Explanation CDATA The value is character data (eval|eval|..) The value must be an enumerated value ID The value is an unique id IDREF The value is the id of another element IDREFS The value is a list of other ids NMTOKEN The value is a valid XML name Page No. 67

SICET Web Technologies NMTOKENS ENTITY ENTITIES NOTATION xml: The value is a list of valid XML names The value is an entity The value is a list of entities The value is a name of a notation The value is predefined

Prepared By: A. Laxmi Kanth

The attribute-default-value can have the following values: Value Explanation #DEFAULT value The attribute has a default value #REQUIRED The attribute value must be included in the element #IMPLIED The attribute does not have to be included #FIXED value The attribute value is fixed Attribute declaration example DTD example: <!ELEMENT square EMPTY> <!ATTLIST square width CDATA "0"> XML example: <square width="100"></square> In the above example the element square is defined to be an empty element with the attributes width of type CDATA. The width attribute has a default value of 0. Default attribute value Syntax: <!ATTLIST element-name attribute-name CDATA "default-value"> DTD example: <!ATTLIST payment type CDATA "check"> XML example: <payment type="check"> Specifying a default value for an attribute, assures that the attribute will get a value even if the author of the XML document didn't include it. Implied attribute Syntax: <!ATTLIST element-name attribute-name attribute-type #IMPLIED> DTD example: <!ATTLIST contact fax CDATA #IMPLIED> XML example: <contact fax="555-667788"> Use an implied attribute if you don't want to force the author to include an attribute and you don't have an option for a default value either. Required attribute Syntax: <!ATTLIST element-name attribute_name attribute-type #REQUIRED> Page No. 68

SICET Web Technologies DTD example: <!ATTLIST person number CDATA #REQUIRED> XML example: <person number="5677">

Prepared By: A. Laxmi Kanth

Use a required attribute if you don't have an option for a default value, but still want to force the attribute to be present. Fixed attribute value Syntax:<!ATTLIST element-name attribute-name attribute-type #FIXED "value"> DTD example:<!ATTLIST sender company CDATA #FIXED "Microsoft"> XML example: <sender company="Microsoft"> Use a fixed attribute value when you want an attribute to have a fixed value without allowing the author to change it. If an author includes another value, the XML parser will return an error. Enumerated attribute values Syntax: <!ATTLIST element-name attribute-name (eval|eval|..) default-value> DTD example: <!ATTLIST payment type (check|cash) "cash"> XML example: <payment type="check"> or <payment type="cash"> XML Namespace In XML, a namespace is used to prevent any conflicts with element names. Because XML allows you to create your own element names, there's always the possibility of naming an element exactly the same as one in another XML document. This might be OK if you never use both documents together. But what if you need to combine the content of both documents? You would have a name conflict. You would have two different elements, with different purposes, both with the same name. Example Name Conflict Imagine we have an XML document containing a list of books. Something like this: <books> <book> <title>The Dream Saga</title> <author>Matthew Mason</author> </book> ... </books> And imagine we want to combine it with the following HTML page: <html> <head> <title>Cool Books</title> Page No. 69

SICET Web Technologies </head> <body> <p>Here's a list of cool books...</p> (XML content goes here) </body> </html>

Prepared By: A. Laxmi Kanth

We will encounter a problem if we try to combine the above documents. This is because they both have an element called title. One is the title of the book, the other is the title of the HTML page. We have a name conflict. What we can do to prevent this name conflict is, create a namespace for the XML document. Example Namespace Using the above example, we could change the XML document to look something like this: <bk:books xmlns:bk="http://somebooksite.com/book_spec"> <bk:book> <bk:title>The Dream Saga</bk:title> <bk:author>Matthew Mason</bk:author> </bk:book> ... </bk:books> We have added the xmlns:{prefix} attribute to the root element. We have assigned this attribute a unique value. This unique value is usually in the form of a Uniform Resource Identifier (URI). This defines the namespace. And, now that the namespace has been defined, we have added a bk prefix to our element names. Now, when we combine the two documents, the XML processor will see two different element names: bk:title (from the XML document) and title (from the HTML document). In the previous lesson, we created a namespace to avoid a name conflict between the elements of two documents we wanted to combine. When we defined the namespace, we defined it against the root element. This meant that the namespace was to be used for the whole document, and we prefixed all child elements with the same namespace. You can also define namespaces against a child node. This way, you could use multiple namespaces within the same document if required. Example Local Namespace Here, we apply the namespace against the title element only: <books> <book> <bk:title xmlns:bk="http://somebooksite.com/book_spec"> The Dream Saga </bk:title> <author>Matthew Mason</author> </book> ... </books>Here, we apply the namespace against the title element only: <books> <book> <bk:title xmlns:bk="http://somebooksite.com/book_spec"> Page No. 70

SICET Web Technologies The Dream Saga </bk:title> <author>Matthew Mason</author> </book> ... </books>

Prepared By: A. Laxmi Kanth

XML Default Namespace The namespaces we created in the previous two lessons involved applying a prefix. We applied the prefix when we defined the namespace, and we applied a prefix to each element that referred to the namespace. You can also use what is known as a default namespace within your XML documents. The only difference between a default namespace and the namespaces we covered in the previous two lessons is, a default namespace is one where you don't apply a prefix. You can also define namespaces against a child node. This way, you could use multiple namespaces within the same document if required. Example Default Namespace Here, we define the namespace without a prefix: <books xmlns="http://somebooksite.com/book_spec"> <book> <title>The Dream Saga</title> <author>Matthew Mason</author> </book> ... </books> When you define the namespace without a prefix, all descendant elements are assumed to belong to that namespace, unless specified otherwise (i.e. with a local namespace). Problematic Characters Some characters have a special meaning in XML. For example, the less than sign (<) marks the beginning of a tag. And, of course, the greater than sign (>) marks the end of the tag. When the XML processor parses the document, it looks for these characters (and others) to determine how to interpret the document. it looks for these characters (and others) to determine how to interpret the document. This is fine, as long as your data doesn't contain any of these characters. But what if it does? What if your data contains say, a less than sign? Imagine you had the following text within an element: 10 < 5. When the XML processor encounters the <, it will assume it's the start of an opening tag. Problem is, it's not. In order to include characters such as < and & etc, you need to use their entity reference instead of the character itself. &lt; < &gt; > &amp; & &quot; " &apos; &apos;

Page No. 71

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Validating Our First XML Now that we have a DTD and XML document, it's time to validate. Fortunately, Macromedia Dreamweaver MX has a built-in validation tool that we can use during development (in "real life" we would use a built-in validator that's part of our application). If you don't already own Dreamweaver, you can get a trial copy. All we have to do is open our XML document (which contains a DTD) in Dreamweaver, then choose File > Check Page > Validate as XML. The result should look a lot like Figure 3.1, "Validating our first case with Dreamweaver MX.". Validating our first XML with Dreamweaver MX.

Do you see how, under Results, it reads No errors or warnings found.? That's what you want to see. In Dreamweaver MX 2004, the results list for a valid document is simply empty, and the status bar beneath the list reads Complete. What happens if some things are out of place? For instance, what if, as a priority, you wrote "Extremely Urgent"? What would happen then? In that case, you'd see an error message like the one in Figure 3.2, "Error resulting from a bad attribute value." below. Error resulting from a bad attribute value.

Notice that Dreamweaver MX tells you where the problem lies (with a specific line number) and provides a description of the problem. In this case, the validator is saying that the value of the priority attribute in your XML document doesn't match any of the possibilities defined in the DTD.
Page No. 72

SICET Web Technologies

Prepared By: A. Laxmi Kanth

XML Schema XML Schema is an XML-based alternative to DTD.An XML schema describes the structure of an XML document.The XML Schema language is also referred to as XML Schema Definition (XSD).The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a DTD. An XML Schema: Defines elements that can appear in a document Defines attributes that can appear in a document Defines which elements are child elements Defines the order of child elements Defines the number of child elements Defines whether an element is empty or can include text Defines data types for elements and attributes Defines default and fixed values for elements and attributes One of the greatest strength of XML Schemas is the support for data types. With support for data types: It is easier to describe allowable document content It is easier to validate the correctness of data It is easier to work with data from a database It is easier to define data facets (restrictions on data) It is easier to define data patterns (data formats) It is easier to convert data between different data types XML Schemas Secure Data Communication When sending data from a sender to a receiver, it is essential that both parts have the same "expectations" about the content. With XML Schemas, the sender can describe the data in a way that the receiver will understand. A date like: "03-11-2004" will, in some countries, be interpreted as 3.November and in other countries as 11.March. However, an XML element with a data type like this: <date type="date">2004-03-11</date> ensures a mutual understanding of the content, because the XML data type "date" requires the format "YYYY-MM-DD". A Simple XML Document Look at this simple XML document called "note.xml": <?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Page No. 73

SICET Web Technologies

Prepared By: A. Laxmi Kanth

A DTD File The following example is a DTD file called "note.dtd" that defines the elements of the XML document above ("note.xml"): <!ELEMENT note (to, from, heading, body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> The first line defines the note element to have four child elements: "to, from, heading, body". Line 2-5 defines the to, from, heading, body elements to be of type "#PCDATA". An XML Schema The following example is an XML Schema file called "note.xsd" that defines the elements of the XML document above ("note.xml"): <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3schools.com" xmlns="http://www.w3schools.com" elementFormDefault="qualified"> <xs:element name="note"> <xs:complexType> <xs:sequence> <xs:element name="to" type="xs:string"/> <xs:element name="from" type="xs:string"/> <xs:element name="heading" type="xs:string"/> <xs:element name="body" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> A Reference to an XML Schema This XML document has a reference to an XML Schema: <?xml version="1.0"?> <note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com note.xsd"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Page No. 74

SICET Web Technologies

Prepared By: A. Laxmi Kanth

The <schema> element is the root element of every XML Schema. <?xml version="1.0"?> <xs:schema> ... ... </xs:schema> The <schema> element may contain some attributes. A schema declaration often looks something like this: <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.w3schools.com" xmlns="http://www.w3schools.com" elementFormDefault="qualified"> ... ... </xs:schema> The following fragment: xmlns:xs="http://www.w3.org/2001/XMLSchema" indicates that the elements and data types used in the schema come from the "http://www.w3.org/2001/XMLSchema" namespace. It also specifies that the elements and data types that come from th e "http://www.w3.org/2001/XMLSchema" namespace should be prefixed with xs: elementFormDefault="qualified" indicates that any elements used by the XML instance document which were declared in this schema must be namespace qualified. Simple Element A simple element is an XML element that can contain only text. It cannot contain any other elements or attributes. However, the "only text" restriction is quite misleading. The text can be of many different types. It can be one of the types included in the XML Schema definition (boolean, string, date, etc.), or it can be a custom type that you can define yourself. You can also add restrictions (facets) to a data type in order to limit its content, or you can require the data to match a specific pattern. Defining a Simple Element The syntax for defining a simple element is: <xs:element name="xxx" type="yyy"/> where xxx is the name of the element and yyy is the data type of the element. XML Schema has a lot of built-in data types. The most common types are:
Page No. 75

SICET Web Technologies

Prepared By: A. Laxmi Kanth

xs:string xs:decimal

xs:integer

xs:boolean

xs:date

xs:time

Example Here are some XML elements: <lastname>Refsnes</lastname> <age>36</age> <dateborn>1970-03-27</dateborn> And here are the corresponding simple element definitions: <xs:element name="lastname" type="xs:string"/> <xs:element name="age" type="xs:integer"/> <xs:element name="dateborn" type="xs:date"/> Default and Fixed Values for Simple Elements Simple elements may have a default value OR a fixed value specified. A default value is automatically assigned to the element when no other value is specified. In the following example the default value is "red": <xs:element name="color" type="xs:string" default="red"/> A fixed value is also automatically assigned to the element, and you cannot specify another value. In the following example the fixed value is "red": <xs:element name="color" type="xs:string" fixed="red"/> What is an Attribute? Simple elements cannot have attributes. If an element has attributes, it is considered to be of a complex type. But the attribute itself is always declared as a simple type. How to Define an Attribute? The syntax for defining an attribute is: <xs:attribute name="xxx" type="yyy"/> where xxx is the name of the attribute and yyy specifies the data type of the attribute. XML Schema has a lot of built-in data types. The most common types are: xs:string xs:decimal xs:integer xs:boolean xs:date xs:time Example Here is an XML element with an attribute: <lastname lang="EN">Smith</lastname> And here is the corresponding attribute definition: <xs:attribute name="lang" type="xs:string"/>

Page No. 76

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Default and Fixed Values for Attributes Attributes may have a default value OR a fixed value specified. A default value is automatically assigned to the attribute when no other value is specified. In the following example the default value is "EN": <xs:attribute name="lang" type="xs:string" default="EN"/> A fixed value is also automatically assigned to the attribute, and you cannot specify another value.In the following example the fixed value is "EN": <xs:attribute name="lang" type="xs:string" fixed="EN"/> Optional and Required Attributes Attributes are optional by default. To specify that the attribute is required, use the "use" attribute: <xs:attribute name="lang" type="xs:string" use="required"/> Restrictions on Content When an XML element or attribute has a data type defined, it puts restrictions on the element's or attribute's content. If an XML element is of type "xs:date" and contains a string like "Hello World", the element will not validate. With XML Schemas, you can also add your own restrictions to your XML elements and attributes. These restrictions are called facets. You can read more about facets in the next chapter. Restrictions on Values The following example defines an element called "age" with a restriction. The value of age cannot be lower than 0 or greater than 120: <xs:element name="age"> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"/> <xs:maxInclusive value="120"/> </xs:restriction> </xs:simpleType> </xs:element> Restrictions on a Set of Values To limit the content of an XML element to a set of acceptable values, we would use the enumeration constraint. The example below defines an element called "car" with a restriction. The only acceptable values are: Audi, Golf, BMW: <xs:element name="car"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Audi"/>
Page No. 77

SICET Web Technologies

Prepared By: A. Laxmi Kanth

<xs:enumeration value="Golf"/> <xs:enumeration value="BMW"/> </xs:restriction> </xs:simpleType> </xs:element> The example above could also have been written like this: <xs:element name="car" type="carType"/> <xs:simpleType name="carType"> <xs:restriction base="xs:string"> <xs:enumeration value="Audi"/> <xs:enumeration value="Golf"/> <xs:enumeration value="BMW"/> </xs:restriction> </xs:simpleType> Note: In this case the type "carType" can be used by other elements because it is not a part of the "car" element. Restrictions on a Series of Values To limit the content of an XML element to define a series of numbers or letters that can be used, we would use the pattern constraint. The example below defines an element called "letter" with a restriction. The only acceptable value is ONE of the LOWERCASE letters from a to z: <xs:element name="letter"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="[a-z]"/> </xs:restriction> </xs:simpleType> </xs:element> The next example defines an element called "initials" with a restriction. The only acceptable value is THREE of the UPPERCASE letters from a to z: <xs:element name="initials"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="[A-Z][A-Z][A-Z]"/> </xs:restriction> </xs:simpleType> </xs:element> The next example also defines an element called "initials" with a restriction. The only acceptable value is THREE of the LOWERCASE OR UPPERCASE letters from a to z:
Page No. 78

SICET Web Technologies

Prepared By: A. Laxmi Kanth

<xs:element name="initials"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="[a-zA-Z][a-zA-Z][a-zA-Z]"/> </xs:restriction> </xs:simpleType> </xs:element> The next example defines an element called "choice" with a restriction. The only acceptable value is ONE of the following letters: x, y, OR z: <xs:element name="choice"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="[xyz]"/> </xs:restriction> </xs:simpleType> </xs:element> The next example defines an element called "prodid" with a restriction. The only acceptable value is FIVE digits in a sequence, and each digit must be in a range from 0 to 9: <xs:element name="prodid"> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/> </xs:restriction> </xs:simpleType> </xs:element> Other Restrictions on a Series of Values The example below defines an element called "letter" with a restriction. The acceptable value is zero or more occurrences of lowercase letters from a to z: <xs:element name="letter"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="([a-z])*"/> </xs:restriction> </xs:simpleType> </xs:element> The next example also defines an element called "letter" with a restriction. The acceptable value is one or more pairs of letters, each pair consisting of a lower case letter followed by an upper case letter. For example, "sToP" will be validated by this pattern, but not "Stop" or "STOP" or "stop":
Page No. 79

SICET Web Technologies

Prepared By: A. Laxmi Kanth

<xs:element name="letter"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="([a-z][A-Z])+"/> </xs:restriction> </xs:simpleType> </xs:element> The next example defines an element called "gender" with a restriction. The only acceptable value is male OR female: <xs:element name="gender"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="male|female"/> </xs:restriction> </xs:simpleType> </xs:element> The next example defines an element called "password" with a restriction. There must be exactly eight characters in a row and those characters must be lowercase or uppercase letters from a to z, or a number from 0 to 9: <xs:element name="password"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="[a-zA-Z0-9]{8}"/> </xs:restriction> </xs:simpleType> </xs:element> Restrictions on Whitespace Characters To specify how whitespace characters should be handled, we would use the whiteSpace constraint. This example defines an element called "address" with a restriction. The whiteSpace constraint is set to "preserve", which means that the XML processor WILL NOT remove any white space characters: <xs:element name="address"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:whiteSpace value="preserve"/> </xs:restriction> </xs:simpleType> </xs:element> This example also defines an element called "address" with a restriction. The whiteSpace constraint is set to "replace", which means that the XML processor WILL
Page No. 80

SICET Web Technologies

Prepared By: A. Laxmi Kanth

REPLACE all white space characters (line feeds, tabs, spaces, and carriage returns) with spaces: <xs:element name="address"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:whiteSpace value="replace"/> </xs:restriction> </xs:simpleType> </xs:element> This example also defines an element called "address" with a restriction. The whiteSpace constraint is set to "collapse", which means that the XML processor WILL REMOVE all white space characters (line feeds, tabs, spaces, carriage returns are replaced with spaces, leading and trailing spaces are removed, and multiple spaces are reduced to a single space): <xs:element name="address"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:whiteSpace value="collapse"/> </xs:restriction> </xs:simpleType> </xs:element> Restrictions on Length To limit the length of a value in an element, we would use the length, maxLength, and minLength constraints. This example defines an element called "password" with a restriction. The value must be exactly eight characters: <xs:element name="password"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:length value="8"/> </xs:restriction> </xs:simpleType> </xs:element> This example defines another element called "password" with a restriction. The value must be minimum five characters and maximum eight characters: <xs:element name="password"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="5"/> <xs:maxLength value="8"/>
Page No. 81

SICET Web Technologies

Prepared By: A. Laxmi Kanth

</xs:restriction> </xs:simpleType> </xs:element> Restrictions for Datatypes Constraint enumeration fractionDigits length maxExclusive maxInclusive maxLength minExclusive minInclusive minLength totalDigits whiteSpace Description Defines a list of acceptable values Specifies the maximum number of decimal places allowed. Must be equal to or greater than zero Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero Specifies the upper bounds for numeric values (the value must be less than this value) Specifies the upper bounds for numeric values (the value must be less than or equal to this value) Specifies the maximum number of characters or list items allowed. Must be equal to or greater than zero Specifies the lower bounds for numeric values (the value must be greater than this value) Specifies the lower bounds for numeric values (the value must be greater than or equal to this value) Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero pattern Defines the exact sequence of characters that are acceptable Specifies the exact number of digits allowed. Must be greater than zero Specifies how white space (line feeds, tabs, spaces, and carriage returns) is handled

What is a Complex Element? A complex element is an XML element that contains other elements and/or attributes. There are four kinds of complex elements: empty elements elements that contain only other elements elements that contain only text elements that contain both other elements and text Note: Each of these elements may contain attributes as well! Examples of Complex Elements A complex XML element, "product", which is empty: <product pid="1345"/> A complex XML element, "employee", which contains only other elements:
Page No. 82

SICET Web Technologies

Prepared By: A. Laxmi Kanth

<employee> <firstname>John</firstname> <lastname>Smith</lastname> </employee> A complex XML element, "food", which contains only text: <food type="dessert">Ice cream</food> A complex XML element, "description", which contains both elements and text: <description> It happened on <date lang="norwegian">03.03.99</date> .... </description> How to Define a Complex Element Look at this complex XML element, "employee", which contains only other elements: <employee> <firstname>John</firstname> <lastname>Smith</lastname> </employee> We can define a complex element in an XML Schema two different ways: 1. The "employee" element can be declared directly by naming the element, like this: <xs:element name="employee"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> If you use the method described above, only the "employee" element can use the specified complex type. Note that the child elements, "firstname" and "lastname", are surrounded by the <sequence> indicator. This means that the child elements must appear in the same order as they are declared. You will learn more about indicators in the XSD Indicators chapter. 2. The "employee" element can have a type attribute that refers to the name of the complex type to use: <xs:element name="employee" type="personinfo"/> <xs:complexType name="personinfo"> <xs:sequence> <xs:element name="firstname" type="xs:string"/>
Page No. 83

SICET Web Technologies

Prepared By: A. Laxmi Kanth

<xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> If you use the method described above, several elements can refer to the same complex type, like this: <xs:element name="employee" type="personinfo"/> <xs:element name="student" type="personinfo"/> <xs:element name="member" type="personinfo"/> <xs:complexType name="personinfo"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> You can also base a complex element on an existing complex element and add some elements, like this: <xs:element name="employee" type="fullpersoninfo"/> <xs:complexType name="personinfo"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="fullpersoninfo"> <xs:complexContent> <xs:extension base="personinfo"> <xs:sequence> <xs:element name="address" type="xs:string"/> <xs:element name="city" type="xs:string"/> <xs:element name="country" type="xs:string"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> Complex Empty Elements An empty XML element: <product prodid="1345" />

Page No. 84

SICET Web Technologies

Prepared By: A. Laxmi Kanth

The "product" element above has no content at all. To define a type with no content, we must define a type that allows elements in its content, but we do not actually declare any elements, like this: <xs:element name="product"> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:integer"> <xs:attribute name="prodid" type="xs:positiveInteger"/> </xs:restriction> </xs:complexContent> </xs:complexType> </xs:element> In the example above, we define a complex type with a complex content. The complexContent element signals that we intend to restrict or extend the content model of a complex type, and the restriction of integer declares one attribute but does not introduce any element content. However, it is possible to declare the "product" element more compactly, like this: <xs:element name="product"> <xs:complexType> <xs:attribute name="prodid" type="xs:positiveInteger"/> </xs:complexType> </xs:element> Or you can give the complexType element a name, and let the "product" element have a type attribute that refers to the name of the complexType (if you use this method, several elements can refer to the same complex type): <xs:element name="product" type="prodtype"/> <xs:complexType name="prodtype"> <xs:attribute name="prodid" type="xs:positiveInteger"/> </xs:complexType> An "elements-only" complex type contains an element that contains only other elements. Complex Types Containing Elements Only An XML element, "person", that contains only other elements: <person> <firstname>John</firstname> <lastname>Smith</lastname> </person> You can define the "person" element in a schema, like this: <xs:element name="person"> <xs:complexType>
Page No. 85

SICET Web Technologies

Prepared By: A. Laxmi Kanth

<xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> Notice the <xs:sequence> tag. It means that the elements defined ("firstname" and "lastname") must appear in that order inside a "person" element. Or you can give the complexType element a name, and let the "person" element have a type attribute that refers to the name of the complexType (if you use this method, several elements can refer to the same complex type): <xs:element name="person" type="persontype"/> <xs:complexType name="persontype"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> A complex text-only element can contain text and attributes. Complex Text-Only Elements This type contains only simple content (text and attributes), therefore we add a simpleContent element around the content. When using simple content, you must define an extension OR a restriction within the simpleContent element, like this: <xs:element name="somename"> <xs:complexType> <xs:simpleContent> <xs:extension base="basetype"> .... .... </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> OR <xs:element name="somename"> <xs:complexType> <xs:simpleContent> <xs:restriction base="basetype"> .... ....
Page No. 86

SICET Web Technologies

Prepared By: A. Laxmi Kanth

</xs:restriction> </xs:simpleContent> </xs:complexType> </xs:element> Tip: Use the extension/restriction element to expand or to limit the base simple type for the element. Here is an example of an XML element, "shoesize", that contains text-only: <shoesize country="france">35</shoesize> The following example declares a complexType, "shoesize". The content is defined as an integer value, and the "shoesize" element also contains an attribute named "country": <xs:element name="shoesize"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:integer"> <xs:attribute name="country" type="xs:string" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> We could also give the complexType element a name, and let the "shoesize" element have a type attribute that refers to the name of the complexType (if you use this method, several elements can refer to the same complex type): <xs:element name="shoesize" type="shoetype"/> <xs:complexType name="shoetype"> <xs:simpleContent> <xs:extension base="xs:integer"> <xs:attribute name="country" type="xs:string" /> </xs:extension> </xs:simpleContent> </xs:complexType> Complex Types with Mixed Content An XML element, "letter", that contains both text and other elements: <letter> Dear Mr.<name>John Smith</name>. Your order <orderid>1032</orderid> will be shipped on <shipdate>2001-07-13</shipdate>. </letter>

Page No. 87

SICET Web Technologies

Prepared By: A. Laxmi Kanth

The following schema declares the "letter" element: <xs:element name="letter"> <xs:complexType mixed="true"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="orderid" type="xs:positiveInteger"/> <xs:element name="shipdate" type="xs:date"/> </xs:sequence> </xs:complexType> </xs:element> Note: To enable character data to appear between the child-elements of "letter", the mixed attribute must be set to "true". The <xs:sequence> tag means that the elements defined (name, orderid and shipdate) must appear in that order inside a "letter" element. We could also give the complexType element a name, and let the "letter" element have a type attribute that refers to the name of the complexType (if you use this method, several elements can refer to the same complex type): <xs:element name="letter" type="lettertype"/> <xs:complexType name="lettertype" mixed="true"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="orderid" type="xs:positiveInteger"/> <xs:element name="shipdate" type="xs:date"/> </xs:sequence> </xs:complexType> XLST XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents. XSLT stands for XSL Transformations. The basic thing about XSLT is that a XML document can be processed with an XSLT (Extensible Stylesheet Language Transformations) as transforming instructions. XSLT is a turing complete programming language which means generally speaking every imaginable transformation can be done . The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or <xsl:transform>. Note: <xsl:stylesheet> and <xsl:transform> are completely synonymous and either can be used!
Page No. 88

SICET Web Technologies

Prepared By: A. Laxmi Kanth

The correct way to declare an XSL style sheet according to the W3C XSLT Recommendation is: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> To get access to the XSLT elements, attributes and features we must declare the XSLT namespace at the top of the document. The xmlns:xsl="http://www.w3.org/1999/XSL/Transform" points to the official W3C XSLT namespace. If you use this namespace, you must also include the attribute version="1.0". To demonstrate all capabilities of XSLT let we use the following example of xml document. The XML input file <catalog> <book> <title>The XHTML 1.0 Web Developement Sourcebook</title> <author>Ian Graham</author> <price>500</price> </book> <book> <title>The XML Specification Guide</title> <author>Ian Graham</author> <price>400</price> </book> <book> <title>Practical Web technologies</title> <author>P. K. Yuen, V. Lau</author> <price>400</price> </book> <book> <title>Foundations of Web technology</title> <author>Ramesh R. Sarukkai</author> <price>350</price> </book> <book> <title>An introduction to XML and Web technologies</title> <author>Anders Mller, Michael I. Schwartzbach</author> <price>300</price> </book> <book> <title>Beginning Web Programming with HTML,XHTML,and CSS </title> <author>Jon Duckett</author> <price>250</price> </book> </catalog>
Page No. 89

SICET Web Technologies

Prepared By: A. Laxmi Kanth

XSL style sheet referene File: (xsltest.xsl) <xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:template match="/"> <xsl:value-of select="//title"/> <xsl:value-of select="//author"/> <xsl:value-of select=//price/> </xsl:template> </xsl:stylesheet> Add the XSL style sheet reference to your XML document (xsltest.xsl) <?xml version="1.0" encoding="ISO-8859-1"?> <?xml-stylesheet type="text/xsl" href="xsltestt.xsl"?> And Load book.xml in browser then you will get out put as : The XHTML 1.0 Web Development Ian Graham500 The <xsl:template> Element The <xsl:template> element is used to build templates. The match attribute is used to associate a template with an XML element. The match attribute can also be used to define a template for the entire XML document. The value of the match attribute is an XPath expression (i.e. match="/" defines the whole document). The <xsl:value-of> Element The <xsl:value-of> element can be used to extract the value of an XML element and add it to the output stream of the transformation: The Output can be any text based format such as HTML, SGML, rich text, LaTeX, plain text, and of course XML. <xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:template match="/"> <html> <body> <h2>Books on Web Technologies</h2> <table border="1"> <tr bgcolor="yellow"> <th>Title</th> <th>Artist</th> <th>Price</th> </tr> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="author"/></td> <td><xsl:value-of select="price"/></td> </tr>
Page No. 90

SICET Web Technologies

Prepared By: A. Laxmi Kanth

</table> </body> </html> </xsl:template> </xsl:stylesheet> Now the output will be: Books on Web Technologies Title Artist Price The XHTML 1.0 Web Development Ian Graham 500 The <xsl:for-each> Element The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set: <xsl:for-each select="catalog/book"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="author"/></td> <td><xsl:value-of select="price"/></td> </tr> </xsl:for-each> Output: Books on Web Technologies Title The XHTML 1.0 Web Developement Sourcebook The XML Specification Guide Practical Web technologies Foundations of Web technology

Artist Ian Graham

Price 500 400 400 350 300 250

Ian Graham P. K. Yuen, V. Lau Ramesh R. Sarukkai Anders Mller, Michael I. An introduction to XML and Web technologies Schwartzbach Beginning Web Programming with Jon Duckett HTML,XHTML,and CSS

We can also filter the output from the XML file by adding a criterion to the select attribute in the <xsl:for-each> element.Legal filter operators are: = (equal) != (not equal) &lt; less than &gt; greater than

Page No. 91

SICET Web Technologies

Prepared By: A. Laxmi Kanth

<xsl:for-each select="catalog/book[author='Ian Graham']"> Output: Books on Web Technologies Title Artist Price The XHTML 1.0 Web Developement Sourcebook Ian Graham 500 The XML Specification Guide Ian Graham 400 <xsl:for-each select="catalog/book[author!='Ian Graham']"> Output: Artist P. K. Yuen, V. Lau Ramesh R. Sarukkai Anders Mller, Michael I. An introduction to XML and Web technologies Schwartzbach Beginning Web Programming with Jon Duckett HTML,XHTML,and CSS <xsl:for-each select="catalog/book[price &lt;300]"> Output: Books on Web Technologies Title Artist Price Beginning Web Programming with HTML,XHTML,and CSS Jon Duckett 250 <xsl:for-each select="catalog/book[price &gt;400]"> Output: Books on Web Technologies Title Artist Price The XHTML 1.0 Web Developement Sourcebook Ian Graham 500 XSLT <xsl:sort> Element The <xsl:sort> element is used to sort the output. Ex: <xsl:for-each select="catalog/book"> <xsl:sort select="title"/> Books on Web Technologies Title Practical Web technologies Foundations of Web technology Price 400 350 300 250

Page No. 92

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Output: Artist Anders Mller, Michael I. An introduction to XML and Web technologies Schwartzbach Beginning Web Programming with Jon Duckett HTML,XHTML,and CSS Foundations of Web technology Ramesh R. Sarukkai Practical Web technologies P. K. Yuen, V. Lau The XHTML 1.0 Web Developement Ian Graham Sourcebook The XML Specification Guide Ian Graham The <xsl:if> Element To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL document. Syntax <xsl:if test="expression"> ...some output if the expression is true... </xsl:if> Ex: <xsl:for-each select="catalog/book"> <xsl:if test="price &gt; 350"> <tr><td><xsl:value-of select="title"/></td> <td><xsl:value-of select="author"/></td> <td><xsl:value-of select="price"/></td> </tr> </xsl:if> OutPut: Books on Web Technologies Title Artist The XHTML 1.0 Web Developement Sourcebook Ian Graham The XML Specification Guide Ian Graham Practical Web technologies P. K. Yuen, V. Lau The <xsl:choose> Element The <xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express multiple conditional tests.
Page No. 93

Books on Web Technologies Title

Price 300 250 350 400 500 400

Price 500 400 400

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Syntax <xsl:choose> <xsl:when test="expression"> ... some output ... </xsl:when> <xsl:otherwise> ... some output .... </xsl:otherwise> </xsl:choose> Ex: <xsl:for-each select="catalog/book"> <tr> <xsl:choose> <xsl:when test="price &gt; 350"> <td bgcolor="cyan"><xsl:value-of select="title"/></td> </xsl:when> <xsl:otherwise> <td bgcolor="lightgreen"><xsl:value-of select="title"/></td> </xsl:otherwise> </xsl:choose> Output: Books on Web Technologies Title Artist The XHTML 1.0 Web Development Sourcebook Ian Graham The XML Specification Guide Ian Graham Practical Web technologies P. K. Yuen, V. Lau Foundations of Web technology Ramesh R. Sarukkai Anders Mller, Michael I. An introduction to XML and Web technologies Schwartzbach Beginning Web Programming with Jon Duckett HTML,XHTML,and CSS Ex: <xsl:choose> <xsl:when test="price &gt; 350"> <td bgcolor="cyan"><xsl:value-of select="title"/></td> </xsl:when> <xsl:when test="price &gt; 300"> <td bgcolor="pink"><xsl:value-of select="title"/></td> </xsl:when> <xsl:otherwise> <td bgcolor="lightgreen"><xsl:value-of select="title"/></td> </xsl:otherwise> </xsl:choose>
Page No. 94

Price 500 400 400 350 300 250

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Output: Books on Web Technologies Title Artist The XHTML 1.0 Web Development Sourcebook Ian Graham The XML Specification Guide Ian Graham Practical Web technologies P. K. Yuen, V. Lau Foundations of Web technology Ramesh R. Sarukkai Anders Mller, Michael I. An introduction to XML and Web technologies Schwartzbach Beginning Web Programming with Jon Duckett HTML,XHTML,and CSS <xsl:variable name="family" select="('Miguel','Louise','Merlyn','Kai','Eden')" as="xs:string*"/> <xsl:value-of select=" for $i in (1 to count($family)) return concat( $family[$i], if ($i = 2) then '*' else (), if ($i = ( count($family) - 1)) then ' and' else if ($i < (count($family) - 1)) then ',' else '' ) "/>

Price 500 400 400 350 300 250

Page No. 95

SICET Web Technologies

Prepared By: A. Laxmi Kanth

UNIT - IV
The JavaBeans Architecture JavaBeans is architecture for both using and building components in Java. This architecture supports the features of software reuse, component models, and object orientation. One of the most important features of JavaBeans is that it does not alter the existing Java language. If you know how to write software in Java, you know how to use and create Beans. The strengths of Java are built upon and extended to create the JavaBeans component architecture. Although Beans are intended to work in a visual application development tool, they don't necessarily have a visual representation at run-time (although many will). What this does mean is that Beans must allow their property values to be changed through some type of visual interface, and their methods and events should be exposed so that the development tool can write code capable of manipulating the component when the application is executed. Bean Development Kit (BDK) is a tool for testing whether your Javabeans meets the JavaBean specification. Follow the instruction provided to install the BDK. Read the documentation and tutorial provided (in particular, "The Java Tutorial, specialized trial on JavaBeans"). BDK comes with a set of sample demo beans. You should try them out and closely study these demo beans before writing our own beans. bdk needed to be installed in a directory with no spaces in it. Features of JavaBeans Compact and Easy JavaBeans components are simple to create and easy to use. This is an important goal of the JavaBeans architecture. It doesn't take very much to write a simple Bean, and such a Bean is lightweight, it doesn't have to carry around a lot of inherited baggage just to support the Beans environment. Portable Since JavaBeans components are built purely in Java, they are fully portable to any platform that supports the Java run-time environment. All platform specifics, as well as support for JavaBeans, are implemented by the Java virtual machine. Introspection Introspection is the process of exposing the properties, methods, and events that a JavaBean component supports. This process is used at run-time, as well as by a visual development tool at design-time. The default behavior of this process allows for the automatic introspection of any Bean. A low-level reflection mechanism is used to analyze the Bean's class to determine its methods. Next it applies some simple design patterns to determine the properties and events that are supported. To take advantage of reflection, you only need to follow a coding style that matches the design pattern. This is an important feature of JavaBeans. It means that you don't have to do anything more than code your methods using a simple convention. If you do, your Beans will automatically support introspection without you having to write any extra code.

Page No. 96

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Customization When you are using a visual development tool to assemble components into applications, you will be presented with some sort of user interface for customizing Bean attributes. These attributes may affect the way the Bean operates or the way it looks on the screen. The application tool you use will be able to determine the properties that a Bean supports and build a property sheet dynamically. This property sheet will contain editors for each of the properties supported by the Bean, which you can use to customize the Bean to your liking. The Beans class library comes with a number of property editors for common types such as float, boolean, and String. If you are using custom classes for properties, you will have to create custom property editors to associate with them. Persistence It is necessary that Beans support a large variety of storage mechanisms. This way, Beans can participate in the largest number of applications. The simplest way to support persistence is to take advantage of Java Object Serialization. This is an automatic mechanism for saving and restoring the state of an object. Java Object Serialization is the best way to make sure that your Beans are fully portable, because you take advantage of a standard feature supported by the core Java platform. This, however, is not always desirable. There may be cases where you want your Bean to use other file formats or mechanisms to save and restore state. In the future, JavaBeans will support an alternative externalization mechanism that will allow the Bean to have complete control of its persistence mechanism. Bean Develop ment Kit: The Bean Development kit is a tool that allows the user to configure and interconnect a set of beans. The user can change the properties of a Bean, link two or more Beans and execute Beans. Start the "beanbox" by running "$bdk\beanbox\run.bat". The Bean Development Kit (BDK) represents a Toolbox, a Bean Box and a Property Window. The Toolbox window that lists the demonstration Beans The BeanBox window that provides an area in which the user can connect the components.

The BDK is also represents a Properties window that Page No. 97

SICET Web Technologies provides an interface through which the user configure a Bean.

Prepared By: A. Laxmi Kanth

Bean co mpo nent exa mple You can construct simple beans applications without writing any Java code using BeanBox. As a first example, you can build a simple "Juggling Duke" application in which Duke will start or stop juggling depending on which of two buttons you push. The first thing to do is add the Juggler Bean. Starting with an empty BeanBox select the Juggler Bean ( ) from the list of Beans in the Toolbox window. Now, placing the cursor anywhere in the BeanBox will cause a Juggler Bean to be inserted in the design form. The hatched border surrounding the Juggler indicates the Juggler bean is the currently selected. Next, you'll need to add a start button and a stop button to control the juggler. Each of these Beans is an instance of the OurButton Bean class. Place an instance of the button ( ) by click on OutButton bean on tool box and place in Bean Box and repeat for the second button.

Page No. 98

SICET Web Technologies

Prepared By: A. Laxmi Kanth

To change the label on the button, edit the label field in the property sheet to read "Start" as well as Stop.

The next step is to specify an event to be fired by the button. A corresponding event-handler method is then selected for the Juggler Bean. Use the edit menu to select an action event to be fired by the start button. Note that in order for this to work, the start button must be selected. Once the actionPerformed menu selection is made, BeanBox enters a state where a line emanates (Red Rubber Band Line) from the start button and follows the mouse as you move it around the window. This indicates that the button is the selected source for the action event, and that your next mouse press should be over the target which defines appropriate event-handler methods, in this case the Juggler. When you drag the line from the start button and release it over the Juggler Bean, a dialog appears listing applicable event handlers defined by the Juggler Bean.

Page No. 99

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Select the startJuggling method as the target for the event, then press OK. Hook up the action event from the stop button to the Juggler's stopJuggling event-handler method. Now you're finished. You should be able to start and stop the juggler by pressing the appropriate button. You can control Duke's juggling speed by manually setting the propery value labeled animationRate in the Juggler's property sheet editor Creating a Bean: Following are the steps required to create a bean: Create a bean source code as a java file in your directory and compile it using javac. Create a manifest file which will identify the .class file as a bean. Create a jar file which will contain the .class file and a .mf file. Copy the jar file into BDKs jar directory. In command line run the beanbox usually we can get our bean in the Toolbox. Java sou rce file:

Java cla ss file: C:\> javac d . Bulb.java Mani fe st File s: A developer must provide a manifest file to indicate which of the components in a jar file are java Beans. S a m p l e c o d e f o r m a n i f e s t f i l e i s a s s h o w n b e l o w :

Page No. 100

SICET Web Technologies

Prepared By: A. Laxmi Kanth

The last line must be terminated with a newline. Save the above file as bulb.mf. It is not necessary that the .mf file name should be same as the .class file name. For our convenience we made both with same name. JAR File s: Before developing your own bean, it is necessary to understand JAR (Java Archieve) files. The reason for this is that tools like bean box expect Bean to be packaged within JAR files. A JAR file allows you to efficiently deploy a set of classes and their resources. A set of bean can control how and when this information is presented. All of these pieces can be checked into jar file. The JAR file are in a compressed form, that makes it faster to download a JAR file than to separately download several uncompressed files. Create a jar file we use the follow the syntax as jar {ctxu}{cfmoM} [jar-file-name] [manifest-file-name] [-c dir] files. Options: c f m x t v o M create a new achieve the first element In the file list is jar file name the second element in the file list is manifest file name files are to be extracted from the achieve the achieve content should be tabulated the verbose should to be provided do not use compression Manifest file not created

In our example we have to give the following syntax in the command line jar cfmv bulb.jar Bulb.mf pros/Bulb.class The 'c' option is used for creating new jar file. The 'm' option indicates that a manifest file is provided. The 'f' option indicates that the filename of the output jar file is provided. The 'v' option enables the verbose mode. The name of the jar file is usually in lowercase. The message after execution will look like this

Copy the jar file into bdks jar directory and use LoadJar from file menu to appear our bean in tool box.

Page No. 101

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Add Properties to Our Bean Component: If you see the properties of MyBulb bean, it will be like this

A bean has properties, which define the attributes of the bean, and can be manipulated by an application builder tool. Javabean Property Naming Convention: For a property called propertyName of type PropertyType, a getter and a setter method must be defined as follows: private PropertyType PropertyName // declare public PropertyType getPropertyName() // getter public void setPropertyName(PropertyType value) // setter For properties of boolean type, the getter shall be: private boolean PropertyName public boolean isPropertyName() // getter for boolean property public void setPropertyName(boolean value) // setter

We can add properties my adding setter and getter methods in the bean component class Page No. 102

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Create Java file, class file, manifest file, then jar file. Load MyBulb.jar - - Now the property window of MyBulb will look like this, see there is now a property called color and assigned a color value as orange.

Add event handling to a bean component: Page No. 103

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Create Java file, class file, manifest file, then jar file. Load MyBulb.jar - - And design like this

Perform Actions for your buttons and select the methods, now you can able to view swithOn and switchOff events (methods) in EventTargetDialog box. We can also use toggle method to perform on and off operations using a single button. INTROSPECTION: Introspection is the process of exposing the properties, methods, and events that a JavaBean component supports. This process is used at run-time, as well as by a visual development tool at design-time. The default behavior of this process allows for the automatic introspection of any Bean. A low-level reflection mechanism is used to analyze the Bean's class to determine its methods. Next it applies some simple design patterns to determine the properties and events that are supported. To take advantage of reflection, you only need to follow a coding style that matches the design pattern. This is an important feature of JavaBeans. It means that you don't have to do anything more than code your methods using a simple convention. If you do, your Beans will automatically support introspection without you having to write any extra code. Makin g an Applet: Page No. 104

SICET Web Technologies

Prepared By: A. Laxmi Kanth

We can make an applet from the beanbox using a menu item called Make Applet from the bean box. In the Bean box we can see this menu item in main menu. Put an already existing bean (say juggler bean) in the bean box and click the Make Applet menu item as shown in the following figure.

If we click this menu item we can get a dialog box as shown in the following figure. Choose the jar file, where the applet will be stored and the name of the applet class. By default, the applet is called MyApplet and is placed in the tmp directory in the beanbox directory.

After selecting a jar file, press the OK button in the dialog box. Then we can see a progress message box. The bean box creates a source code file for the applet and a sample HTML file containing the proper <APPLET> tag, compiles the source code into a .class file, and stores the .class files and any necessary support files into jar first that are referenced by the HTML file. Bean Properties A bean property is a named attribute of a bean that can affect its behavior or appearance. Examples of bean properties include color, label, font, font size, and display size. The JavaBeans specification defines the following types of bean properties: Simple A bean property with a single value whose changes are independent of changes in any other property. Indexed A bean property that supports a range of values instead of a single value. Page No. 105

SICET Web Technologies

Prepared By: A. Laxmi Kanth

Bound A bean property for which a change to the property results in a notification being sent to some other bean. Constrained A bean property for which a change to the property results in validation by another bean. The other bean may reject the change if it is not appropriate. Bound Properties: Bound properties are the properties that can be connected to another property of the same type in a different bean, so that when the soruce beans property value changes, the target beans property changes to the same value. But some beans only have these bound properties. For example put the jelly bean in our composite BeanBox. 1. Select the jelly bean we can get a menu item as Bind Property in the Edit menu. 2. After pressing that menu item we can get a dialog box which will ask us to select the source property. Selecting a source property (say color). 3. A target line will appear, target it to any object (say BeanBox window) and select the Target property. 4. Now select the property as background 1) 2)

3)

4)

5. We can get the bean box background as same as the jelly Beans background color. If you change the color property of jelly bean bean box background will automatically changes.

Page No. 106

SICET Web Technologies

Prepared By: A. Laxmi Kanth

PERS IS TENCE : Per si stence i s the abi lity to sto re the ob je ct on the di sk in a par ticular state a nd retriev e the ob je ct i n the same sta te in t he futur e from t he di sk. Thi s p ro ce ss i s called Se rializatio n. Pe r si ste nce i s t he o ne of the key te chno logie s of bea ns. Thi s pr ovide s a mea ns fro b eans state a nd co nne ctio ns to be sto red w hen a bea n is unl oad fr om t he v irtual m achi ne, m o st co mmo nly by saving the file on the disk. Whene ver we sele ct save fr om the me nu in the Bea nBo x file menu , java u se s obje ct serializati on t o the curre nt co nte nts and prope rtie s of, and conne ctio ns between, the bean in the bean box. Whe n we sele ct Load fr o m the File menu , java u se s de serializat ion to re st ore not onl y the beans but al so their p rope rtie s and co nne ctio ns. In the beanb ox we f ind a menu item SerializeComponent, when we pre ss thi s me nu item we get a save dialog box which will ask us to save that bean a s a serialized compo ne nt. By conve ntio n, cu sto mized be ans are save d in the file s wit h a . se r e xtension, o ne bea n p e r file. Here ser stand s fo r se rialized. When a bea n object is saved t hr ou gh se ria lization, all of the val ue s of the variable s of t he ob je ct are saved . In thi s way, any p ro pert y change s a re car ried along with the obje ct . The only exce ptio n to thi s is va riable s that are identified as tra nsient. T he val u es of the se va riable s a re not se rialized.

Page No. 107

S-ar putea să vă placă și