Sie sind auf Seite 1von 39

STYLE SHEETS

HOME> TUTORIALS> HTML > Intermediate > STYLE SHEETS

By now you should be happy with altering text in terms of size, colour, font and other things. But for example if you want all your Heading tags to be italicised it can be a drag putting in hundreds and hundreds of <I> and </I> tags. If only there was a way to alter the style of these ! But there is !! These are called style sheets. They will come to no surprise to many of you who have used style sheets in other applications such as word processing or DTP packages These are not just the current in thing but are being actively encouraged as good HTML. Further revisions will take them more & more into account (other editing tags will be dropped in their favour) There are currently 3 ways of using style sheets Inline Style Sheets These are set into the document to define attributes to areas of text Document level Style Sheets Also set into document but cover the whole document External Style Sheets The document links to an external sheet. Useful if you want to create a consistent one across all your web pages You can combine them to give your document extra oomph!!. This technique is calledcascading style sheets and is described later In the examples below we use the following style sheet properties color defines text colour. Either in RGB code or colour name font-style defines special style like italic or bold

font-family defines the font type e.g. font-family: times new roman; If more than one listed e.g. font-family: comic sans ms, serif sans, arial; Then a browser will use the first it has background defines background colour. Either in RGB code or colour name. (Also can set background image see library) some more style sheet properties are listed together with RGB and colour names in our HTMLresource library

Inline Style Sheets


This is the simplest approach. In any tag you just include a style attribute which defines a style sheet property e.g. <h1 style = "color: red; font-style: bold;">This is a big italic red header</h1> <h1>Hang on I am not red or in italics.hmm.....</h1> gives rise to this

This is a big italic red header Hang on I am not red or in italics.hmm.....


As you can see the effect doesn't carry on once the defining tag is closed. You can use them in the middle of text using the <span> tag e.g. <p> <span style="color: red">I am Red</span> whereas I am not </p> I am Red whereas I am not

Why not just use physical style and content tags like font text = red and <i> I hear you say!! Well there are some advantages You can set some factors such as giving a chunk of text a background. You can divide areas of text up with <div> tags e.g. <p> <span style ="background: skyblue;">I have blue behind me</span> I am normal I have blue behind me I am normal These clearly have their limitations. But can be useful in conjunction with other style sheets

Document Level Style Sheets


Now we're motoring ! If you felt Inline style was fiddily & wishy washy, then this should impress you. With Document level style sheets you can define a consistent style for all your text components You need to place this in the <head> tags of your document here is an example (the attribute type = "text/cps" just lets the browser know its it is a text style sheet. For most browsers its not needed) <head> <title>Document level Style sheet example</title> <style type = "text/css"> h1 {color: aqua; font-style: italic; text-align: center} h2 {color: #0000FF; background: khaki; font-family: serif, sans-serif;} p {font-style: bold; font-family: comic sans ms, arial;} dt {color: aqua;} dt em {color: red;}

</style> </head> Now view a page with this style sheet which explains everything between the <style tags> As you can see you get a document wide approach. It can also be set to react to certain editing changes (like the use of <em> tags with defined terms in the example)

External Style Sheets


The principles of external style sheets only differ from document level style sheets in one respect. Instead of defining all the styles on the document, the style is defined by a separate style sheet file (called a .css file). The advantage is that if you want the same style sheet across all your documents you don't have to slavishly copy (or cut and paste !) the same <style> tags and attributes. It also means you can also alter the layout of all linked files just by changing the .css file rather than ploughing through each HTMLdocument (i.e.. You could change all files with a linked external style sheet in a website just by replacing the .css file) You don't need a special editor to create a .css file. Notepad or any basic text editor will do. Say you wanted to use the style sheet described in document level style sheets simply enter the following into notepad h1 {color: aqua; font-style: italic; text-align: center} h2 {color: #0000FF; background: khaki; font-family: serif, sans-serif;} p {font-style: bold; font-family: comic sans ms, arial;} dt {color: aqua;} dt em {color: red;}

select save as and alter save as type to read all files. Find your web folder and in file name enter your style sheet name plus .css (e.g. mystyle.css) To link HTML documents to external style sheets use must place a <link> tag in the <head> tags here we are using the .css file called mystyle.css <head> <link rel="stylesheet" type = "text/css" href = "mystyle.css"> </head> We've created a page which uses our mystyles.css as its External style sheet. Have a look In it there is a link to an identical page but which is linked to a second style sheet file called mystyle2.css. Other than that the HTML editing remains the same. It gives you an idea of the effect of changing a .css file without altering HTML documents We use a .css file for this site to control our links

CASCADING STYLE SHEETS


You've probably seen the term before , but what are cascading style sheets? Well, essentially it means several style sheets can be used in a document each influencing the layout slightly (or causing a cascade of style. This is what W3C want you to be doing for page layout and it can be very effective For example your site could have a common external style sheet to give a like feel throughout your site. Then further document level or in line style sheets could be used to shape an individual document's feel If there is conflict between style sheets (e.g. your .css file says all header should be blue and your <style> says red) The "closer" style sheet will take precedence. Therefore Inline style sheets win over document level with external style sheets having the least power.
111111111111111111111111111

What is a Style?
A style is a rule, or a command, telling a browser how to display a particular HTML element. For instance, a style could specify that all

<h1> elements should be displayed in red and in a

different typeface than the rest of the text. Styles can stand alone or can be organized into style sheets.

style rule: a command that tells a user agent how to display a particular element
There are three ways to include styles in documents:

o o o

inline styles, document-level style sheets, and external style sheets.

You can apply one or more of these to a given document. The reason they are called Cascading Style Sheets is because of how a browser resolves conflicts when more than one style appears to apply to the same element. We will discuss this in more detail later, but the general rule is that the most local and/or recent style takes priority.

Which one to use?


Which approach you should use to adding styles to your documents depends on what you are doing. If you want to unify a group of documents so that they all have the same formatting, then you should have your style sheets stored externally and imported into each document. If you are only formatting one document, then it is perhaps best to include the style sheets as a document level style sheet at the top of the document. Inline styles should be reserved for oneshot formatting, normally as an exception to other style sheets.

Inline Styles

inline style: a style that is specified within the body of a markup tag as an attribute of that tag
The inline style is the easiest way to define a style. It is useful for circumstances where you want to format a single item in a specific way. To define an inline style, you make use of thestyle attribute within the tag you want to format the content of. The value the

style attribute takes is a semi-colon separated list of style rules. For instance,

<p style="color: #660000; font-family: 'Courier New', Courier, monospace; fontweight: bold; padding-left: 2em"> could be used to get the above line of code to look like it does. Any HTML element can take inline style rules. <img src="image.png" style="border; 2px solid red;" /> <table style="max-width: 600px;"> <b style="font-size: 1.2em; font-weight: 500;">

You can even use the style attribute with the

<font> tag to set font attributes. There are two <font> tags are deprecated in

problems with this however. One, it would be redundant. Two,

favor of style sheets. I only bring it up because I often see people do just this thing. Use one if you need backward compatability and the other if you need to adhere to standards, but don't do both. wrong by way of redundancy --

<font style="color: red;">

The advantage to inline styles is that they allow formatting commands for specific elements to be immediately visible in the code and therefore easy to find. However, it is also harder to maintain pages with inline styles, since you have to go through and change each instance of the inline style. Inline styles are also very useful where you have modularized your code and want the style rules to stay with the modules they affect. If you have the same menu copied as a module into every page in your site, then it might make sense to style that menu with inline style rules. This means that you don't need to account for the menu styling in every page you copy it into.

Document Level Style Sheets


document-level style sheet: a collection of style rules enclosed in <style> tags in the header of the document
A preferred method of using styles is to put all the styles at the top of the document in a document-level style sheet. To create a document-level style sheet you place the style rules within

<style> tags in the

header section of the document. It is like including one document inside another. Everything between the tags are considered part of the style rules for the page. A really simple document-level style sheet might look like this: <style> blockquote { color: blue; font-style: italic } </style>

<style> tag should not be confused with a style attribute. They are both for applying

styles to documents, but in slightly different ways. When using document-level style sheets, the style rules should appear within HTML comments. This way browsers that do not understand the style tags will not display the content between the tags as part of the document. Browsers that do recognize style tags will ignore the HTML comments in the style definitions since they are not using the HTML parser to interpret them, but rather the CSS parser. CSS comments look like C programming language comments (/* comment */). <style> <!-/* set blockquotes in blue italic */ blockquote { color: blue; font-style: italic } --> </style>

The HTML comment tags are the only HTML that should appear in the style sheet. Everything else should be properly formed CSS. This is wrong, since it has an HTML tag inside it.

<style> <!-/* set blockquotes in blue italic */ <blockquote> { color: blue; font-style: italic } --> </style>

The

<style> tag should also have a type definition indicating whether it is a CSS style sheet

(type="text/css") or a JavaScript style sheet (type="text/javascript") style sheet. We are only going to talk about CSS here, since JavaScript style sheets are specific to older versions of Netscape and Netscape has ceased supporting them. The

type attribute refers to the MIME type of the content. MIME stands for Multipart Internet

Mail Extension. It is a standard which defines how to make systems aware of the type of content being included in e-mail messages. The primary component of MIME types is a hierarchical labeling system that declares what category of content the document contains and what what specific type it is within that category. For instance, a plain text document is of type type

text/plain and a JPEG image is of

image/jpeg. These types can then be associated programmatically with applications

that can read those MIME types. It has proved to be a useful enough protocol that most applications these days make use of MIME types to determine what sort of document they are trying to read. Any included content that is not of the same MIME type as the main document should have the MIME type specified. Our completed simple document-level style sheet looks like this. I have added a few more style rules so you can get a better feel of the method. <html> <head> <title>sample document</title> <style type="text/css"> <!-/* set blockquotes in blue italic */ blockquote { color: blue; font-style: italic } /* hide borders on image hyperlinks */ img { border: 0px; } /* set basic paragraph styling */ p { margin-top: 1.0em;

margin-bottom: 0.5em; line-height: 1.5em; } --> </style> </head> <body> [ content goes here ] </body> </html>

External Style Sheets


external style sheet: a collection of style rules stored in an external fime and copied into the document when it is loaded into the application
To maintain consistency across a site, you can use external style sheets rather than style sheets internal to you document. You can copy external style sheets into a page when loading, allowing for more dynamic modification of site layouts, as well as standardization across pages. External style sheets are stored in their own text file ending in a

.css suffix.

To include an external style sheet into a document, you can either link it to the current document, or you can import it.

@import
The

@import command is (as of mid-2002) only supported by Explorer, but allows you to @import command is a CSS <style> tags.

import style sheet rules into a document-level style sheet. The

command and is used inside the CSS code, which is to say between the <style> <!-@import url(styles/general.css); --> </style>

The

@import command can be used as many times as necessary to copy in additional style

sheets into the same document. <style>

<!-@import url(styles/general.css); @import url(styles/special_case1.css); @import url(styles/special_case2.css); --> </style>

The benefit of the import tag, when it becomes fully supported, it that it will allow you to create style sheet families. By nesting imported style sheets, you will be able to have imported style sheets import their own style sheets. This means that you will be able to create style sheet libraries, rather than include duplicate code in multiple style sheets. It is also useful for dealing with backwards compatability, where basic styling is put in an inline or external style sheet and then more advanced styling rules that only work in newer browsers are imported in. Thus, only those that understand the When importing, the sheet.

@import command will try to import the advanced style rules.

@import command should occur before all other style rules in the style

Linking Style Sheets


Linking style sheets does not have as much flexibility as importing them, but it does work in most browsers. Older browsers can only link one style sheet to a document. Newer browsers provide support for loading multiple style sheets. To link to a style sheet you use the

<link> tag in the header section of the document.

<link rel="stylesheet" type="text/css" href="styles/general.css">

The three attributes of the tag are as follows:

href
The URL for the style sheet.

rel
The relationship of the document being linked to the current document. In this case, the document in question is the style sheet for the current document.

type
The MIME type of the document begin linked, which in this case istext/css. We will discuss MIME types when we talk more about the header tags. The external style sheet should only contain style rules, with no HTML content. It should not even have

<style> tags. Although if you want to be complete to the

point of overkill you can include them as comments at the top and bottom of the external document, but this is not recommended. (Yes, there is a reason for including commented<style> tags in an external CSS file. It has to do with bluffing some CSS editors into displaying the code with the correct color coding.)

If you load multiple style sheets, they will all be applied in the order linked to. If you want to provide a choice of style sheets that are applied one at a time, then you want to use the

<link> tag with a differentrel value.

<link rel="alternate stylesheet" type="text/css" href="styles/specific.css">

The

alternate stylesheet value defines the style sheet being linked to.

The user can then select to use this style sheet instead of the default one. The most recent versions of Netscape and Opera allow you to select between alternate style sheets. In Netscape, select View, Use Style on the menu. Opera has a toggle button on the address bar to turn style sheets on and off (well, really to switch between the author's style sheets and the user's style sheets). When there are alternate style sheets, a drop down indicator will appear next to this button indicating there are multiple options to select from. You can also get there through the View menu. As of Internet Explorer 6, MSIE does not yet appear to support alternate style sheets.

11111111111111111
This is my first ever using mod operator. What I've done so far is declare and initialize a variable and parsed the string to an integer. I used a if statements to determine whether the remainder is an even or odd number. Then I used document.write to display the output for each if statement. But the output is not showing in the browser. The error console message is that I have an invalid assignment on the left-hand side. I tried switching the left-hand side to the right-hand side but the error is still invalid on the left-hand side. The other thing is I'm not sure whether I should be using the parse since I read that the mod operator attempts to convert the string to a number. But I'm a little confused on this. Anyway, here is the code: Any suggestions? <?xml version ="1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-strict.dtd"> <html xmlns - "http://www.w3.org/1999/xhtml> <html> <head>

<script type="text/javascript"> //Declare variables var num = 18; //converts to integer num = parseInt(num); //write to output if(num % 6 = 0){ document.write(% + "<h2> is an even number</h2>"); } if(num % 6 != 0){ document.write(% + "<h2> is a odd number</h2>"); } //end if

</script> </head> <body> bool IsNumberEven(int number) { if (number%2 == 0) return true; return false; }
1111111111111

XML stands for eXtensible Markup Language. XML is designed to transport and store data. XML is important to know, and very easy to learn.
XML was designed to transport and store data. HTML was designed to display data.

What You Should Already Know


Before you continue you should have a basic understanding of the following:

HTML

JavaScript

If you want to study these subjects first, find the tutorials on our Home page.

What is XML?

XML XML XML XML XML XML stands for EXtensible Markup Language is a markup language much like HTML was designed to carry data, not to display data tags are not predefined. You must define your own tags is designed to be self-descriptive is a W3C Recommendation

The Difference Between XML and HTML


XML is not a replacement for HTML. XML and HTML were designed with different goals:

XML was designed to transport and store data, with focus on what data is HTML was designed to display data, with focus on how data looks

HTML is about displaying information, while XML is about carrying information.

XML Does Not DO Anything


Maybe it is a little hard to understand, but XML does not DO anything. XML was created to structure, store, and transport information. The following example is a note to Tove, from Jani, stored as XML:

<note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>


The note above is quite self descriptive. It has sender and receiver information, it also has a heading and a message body. But still, this XML document does not DO anything. It is just information wrapped in tags. Someone must write a piece of software to send, receive or display it.

With XML You Invent Your Own Tags

The tags in the example above (like <to> and <from>) are not defined in any XML standard. These tags are "invented" by the author of the XML document. That is because the XML language has no predefined tags. The tags used in HTML are predefined. HTML documents can only use tags defined in the HTML standard (like <p>, <h1>, etc.). XML allows the author to define his/her own tags and his/her own document structure.

XML is Not a Replacement for HTML


XML is a complement to HTML. It is important to understand that XML is not a replacement for HTML. In most web applications, XML is used to transport data, while HTML is used to format and display the data. My best description of XML is this: XML is a software- and hardware-independent tool for carrying information.

XML is a W3C Recommendation


XML became a W3C Recommendation on February 10, 1998. To read more about the XML activities at W3C, please read our W3C Tutorial.

XML is Everywhere
XML is now as important for the Web as HTML was to the foundation of the Web. XML is the most common tool for data transmissions between all sorts of applications.

An Example XML Document


XML documents use a self-describing and simple syntax:

<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
The first line is the XML declaration. It defines the XML version (1.0) and the encoding used (ISO-8859-1 = Latin-1/West European character set).

The next line describes the root element of the document (like saying: "this document is a note"):

<note>
The next 4 lines describe 4 child elements of the root (to, from, heading, and body):

<to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body>


And finally the last line defines the end of the root element:

</note>
You can assume, from this example, that the XML document contains a note to Tove from Jani. Don't you agree that XML is pretty self-descriptive?

XML Documents Form a Tree Structure


XML documents must contain a root element. This element is "the parent" of all other elements. The elements in an XML document form a document tree. The tree starts at the root and branches to the lowest level of the tree. All elements can have sub elements (child elements):

<root> <child> <subchild>.....</subchild> </child> </root>


The terms parent, child, and sibling are used to describe the relationships between elements. Parent elements have children. Children on the same level are called siblings (brothers or sisters). All elements can have text content and attributes (just like in HTML).

Example:

The image above represents one book in the XML below:

<bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
The root element in the example is <bookstore>. All <book> elements in the document are contained within <bookstore>. The <book> element has 4 children: <title>,< author>, <year>, <price>.

The syntax rules of XML are very simple and logical. The rules are easy to learn, and easy to use.

All XML Elements Must Have a Closing Tag


In HTML, some elements do not have to have a closing tag:

<p>This is a paragraph. <br>


In XML, it is illegal to omit the closing tag. All elements must have a closing tag:

<p>This is a paragraph.</p> <br />


Note: You might have noticed from the previous example that the XML declaration did not have a closing tag. This is not an error. The declaration is not a part of the XML document itself, and it has no closing tag.

XML Tags are Case Sensitive


XML tags are case sensitive. The tag <Letter> is different from the tag <letter>. Opening and closing tags must be written with the same case:

<Message>This is incorrect</message> <message>This is correct</message>


Note: "Opening and closing tags" are often referred to as "Start and end tags". Use whatever you prefer. It is exactly the same thing.

XML Elements Must be Properly Nested


In HTML, you might see improperly nested elements:

<b><i>This text is bold and italic</b></i>


In XML, all elements must be properly nested within each other:

<b><i>This text is bold and italic</i></b>


In the example above, "Properly nested" simply means that since the <i> element is opened inside the <b> element, it must be closed inside the <b> element.

XML Documents Must Have a Root Element


XML documents must contain one element that is the parent of all other elements. This element is called the root element.

<root> <child> <subchild>.....</subchild> </child> </root>

XML Attribute Values Must be Quoted


XML elements can have attributes in name/value pairs just like in HTML. In XML, the attribute values must always be quoted. Study the two XML documents below. The first one is incorrect, the second is correct:

<note date=12/11/2007> <to>Tove</to> <from>Jani</from> </note> <note date="12/11/2007"> <to>Tove</to> <from>Jani</from> </note>
The error in the first document is that the date attribute in the note element is not quoted.

Entity References
Some characters have a special meaning in XML. If you place a character like "<" inside an XML element, it will generate an error because the parser interprets it as the start of a new element. This will generate an XML error:

<message>if salary < 1000 then</message>


To avoid this error, replace the "<" character with an entity reference:

<message>if salary &lt; 1000 then</message>


There are 5 predefined entity references in XML: &lt; &gt; &amp; &apos; &quot; < > & ' " less than greater than ampersand apostrophe quotation mark

Note: Only the characters "<" and "&" are strictly illegal in XML. The greater than character is legal, but it is a good habit to replace it.

Comments in XML

The syntax for writing comments in XML is similar to that of HTML. <!-- This is a comment -->

White-space is Preserved in XML


HTML truncates multiple white-space characters to one single white-space: HTML: Output: Hello Hello Tove Tove

With XML, the white-space in a document is not truncated.

XML Stores New Line as LF


In Windows applications, a new line is normally stored as a pair of characters: carriage return (CR) and line feed (LF). In Unix applications, a new line is normally stored as an LF character. Macintosh applications also use an LF to store a new line. XML stores a new line as LF.

What is an XML Element?


An XML element is everything from (including) the element's start tag to (including) the element's end tag. An element can contain:

other elements text attributes or a mix of all of the above...

<bookstore> <book category="CHILDREN"> <title>Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title>Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>

In the example above, <bookstore> and <book> have element contents, because they contain other elements. <book> also has an attribute (category="CHILDREN"). <title>, <author>, <year>, and <price> have text content because they contain text.

XML Naming Rules


XML elements must follow these naming rules:

Names Names Names Names

can contain letters, numbers, and other characters cannot start with a number or punctuation character cannot start with the letters xml (or XML, or Xml, etc) cannot contain spaces

Any name can be used, no words are reserved.

Best Naming Practices


Make names descriptive. Names with an underscore separator are nice: <first_name>, <last_name>. Names should be short and simple, like this: <book_title> not like this: <the_title_of_the_book>. Avoid "-" characters. If you name something "first-name," some software may think you want to subtract name from first. Avoid "." characters. If you name something "first.name," some software may think that "name" is a property of the object "first." Avoid ":" characters. Colons are reserved to be used for something called namespaces (more later). XML documents often have a corresponding database. A good practice is to use the naming rules of your database for the elements in the XML documents. Non-English letters like are perfectly legal in XML, but watch out for problems if your software vendor doesn't support them.

XML Elements are Extensible


XML elements can be extended to carry more information. Look at the following XML example:

<note> <to>Tove</to> <from>Jani</from> <body>Don't forget me this weekend!</body> </note>

Let's imagine that we created an application that extracted the <to>, <from>, and <body> elements from the XML document to produce this output:

MESSAGE To: Tove From: Jani Don't forget me this weekend!

Imagine that the author of the XML document added some extra information to it:

<note> <date>2008-01-10</date> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Should the application break or crash? No. The application should still be able to find the <to>, <from>, and <body> elements in the XML document and produce the same output. One of the beauties of XML, is that it can be extended without breaking applications.

11111111111111111111

XML Tutorial - Embedding XML in HTML


Page 1 of 2

Overview

In this chapter you will learn : o How to embed XML into HTML? o What are the various ways to get XML data source?
o

What is Data Binding?

XML can be used to store data inside HTML documents. XML data can be stored inside HTML pages as "Data Islands". As HTML provides a way to format and display the data, XML stores data inside the HTML documents. The data contained in an XML file is of little value unless it can be displayed, and HTML files are used for that purpose. The simple way to insert XML code into an HTML file is to use the <xml> tag. The XML tag informs, the browser that the contents are to be parsed and interpreted using the XML parser. Like most other HTML tags, the <xml> tag has attributes. The most important attribute is the ID, which provides for the unique naming of the code. The contents of the XML tag come from one of two sources : inline XML code or an imported XML file.

If the code appears in the current location , it's said to be inline.

Example Embedding XML code inside an HTML File. <html> <xml Id = msg> <message> <to> Visitors </to> <from> Author </from> <Subject> XML Code Islands </Subject> <body> In this example, XML code is embedded inside HTML code </body> </message> </xml> </html>

The efficient way is to create a file and import it. You can easily do so by using the SRC attribute of the XML tag.

Syntax <xml Id = msg SRC = "example1.xml"> </xml>

Data Binding

Data binding involves mapping, synchronizing, and moving data from a data source, usually on a remote server, to an end user's local system where the user can manipulate the data. Using data binding means that after a remote server transmits data, the user can perform some minor data manipulations on their own local system. The remote server does not have to perform all the data manipulations nor repeatedly transmit variations of the same data.

Data binding involves moving data from a data source to a local system, and then manipulating the data, such as, searching, sorting, and filtering, it on the local system. When you bind data in this way, you do not have to request that the remote server manipulate the data and then retransmit the results; you can perform some data manipulation locally. In data binding, the data source provides the data, and the appropriate applications retrieve and synchronize the data and present it on the terminal screen. If the data changes, the applications are written so they can alter their presentation to reflect those changes. Data binding is used to reduce traffic on the network and to reduce the work of the Web server, especially for minor data manipulations. Binding data also separates the task of maintaining data from the tasks of developing and maintaining binding and presentation programs.

Summary

In this chapter you have learnt


o o o

Embedding of XML into HTML. Various sources of content for XML tag. About data binding.

Review Questions Fill in the Blanks


i. ii. iii. iv. v. When XML data is stored inside HTML pages, it is called as _________. The XML code can be inserted into an HTML file with the use of ______ tag. ______ attribute of XML tag provides for the unique naming of the code. The XML data can be placed as _______ or as an _______ file. ______ allows browser to retrieve data from the database.

Solutions i. ii. iii. iv. v. Data Islands <XML> ID inline, imported XML Data binding

1111111111111
With CSS (Cascading Style Sheets) you can add display information to an XML document.

Displaying your XML Files with CSS?


It is possible to use CSS to format an XML document. Below is an example of how to use a CSS style sheet to format an XML document: Take a look at this XML file: The CD catalog Then look at this style sheet: The CSS file Finally, view: The CD catalog formatted with the CSS file Below is a fraction of the XML file. The second line links the XML file to the CSS file:

<?xml version="1.0" encoding="ISO-8859-1"?> <?xml-stylesheet type="text/css" href="cd_catalog.css"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10.90</PRICE> <YEAR>1985</YEAR>

. . . </CATALOG>

</CD> <CD> <TITLE>Hide your heart</TITLE> <ARTIST>Bonnie Tyler</ARTIST> <COUNTRY>UK</COUNTRY> <COMPANY>CBS Records</COMPANY> <PRICE>9.90</PRICE> <YEAR>1988</YEAR> </CD>

Formatting XML with CSS is not the most common method. W3C recommends using XSLT instead. See the next chapter.

1 1111111111

Introduction
You have an XML document and you need to convert it into a more readable file format. For example, you have personnel data that is stored as an XML document and you need to display it on a Web page or in a text file.

Solution
The solution for this is to use an XSLT stylesheet to transform the XML into another format using theXslTransform class. In the example code, we are transforming some personnel data from a fictitious business stored in Personnel.xml. First, we load the stylesheet for generating HTML output. Then we perform thetransformation to HTML via XSLT using the PersonnelHTML.xsl stylesheet. After that, we transform the data to comma-delimited format using the PersonnelCSV.xsl stylesheet:
Collapse | Copy Code
public static void TransformXML( ) { // Create a resolver with default credentials. XmlUrlResolver resolver = new XmlUrlResolver( ); resolver.Credentials = System.Net.CredentialCache.DefaultCredentials; // transform the personnel.xml file to HTML XslTransform transform = new XslTransform( ); // load up the stylesheet transform.Load(@"..\PersonnelHTML.xsl",resolver); // perform the transformation transform.Transform(@"..\Personnel.xml",@"..\Personnel.html",resolver); // transform the personnel.xml file to comma delimited format // load up the stylesheet transform.Load(@"..\PersonnelCSV.xsl",resolver); // perform the transformation

transform.Transform(@"..\Personnel.xml", @"..\Personnel.csv",resolver); }

The Personnel.xml file contains the following items:


Collapse | Copy Code
<?xml version="1.0" encoding="utf-8"?> <Personnel> <Employee name="Shahab" title="Customer Service" companyYears="1"/> <Employee name="Noosha" title="Manager" companyYears="12"/> <Employee name="NavidChas" title="Salesman" companyYears="3"/> <Employee name="Mehrdad" title="CEO" companyYears="27"/> <Personnel>

The PersonnelHTML.xsl stylesheet looks like this:


Collapse | Copy Code
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xsl:template match="/"> <html> <head /> <body title="Personnel"> <xsl:for-each select="Personnel"> <p> <xsl:for-each select="Employee"> <xsl:if test="position( )=1"> <table border="1"> <thead> <tr> <td>Employee Name</td> <td>Employee Title</td> <td>Years with Company</td> </tr> </thead> <tbody> <xsl:for-each select="../Employee"> <tr> <td> <xsl:for-each select="@name"> <xsl:value-of select="." /> </xsl:for-each> </td> <td> <xsl:for-each select="@title"> <xsl:value-of select="." /> </xsl:for-each> </td> <td> <xsl:for-each select="@companyYears"> <xsl:value-of select="." /> </xsl:for-each> </td> </tr> </xsl:for-each> </tbody>

</table> </xsl:if> </xsl:for-each> </p> </xsl:for-each> </body> </html> </xsl:template> </xsl:stylesheet>

Here is the HTML source:


Collapse | Copy Code
<html xmlns:xs="http://www.w3.org/2002/XMLSchema"> <head> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body title="Personnel"> <p> <table border="1"> <thead> <tr> <td>Employee Name</td> <td>Employee Title</td> <td>Years with Company</td> </tr> </thead> <tbody> <tr> <td>Shahab</td> <td>Customer Service</td> <td>1</td> </tr> <tr> <td>Noosha</td> <td>Manager</td> <td>12</td> </tr> <tr> <td>Navid</td> <td>Salesman</td> <td>3</td> </tr> <tr> <td>Mehrdad</td> <td>CEO</td> <td>27</td> </tr> </tbody> </table> </p> </body> </html>

The comma-delimited output is generated using PersonnelCSV.xsl and Personnel.xml; the stylesheet is shown here:
Collapse | Copy Code

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns: xs="http://www.w3.org/2002/XMLSchema"> <xsl:output method="text" encoding="UTF-8"/> <xsl:template match="/"> <xsl:for-each select="Personnel"> <xsl:for-each select="Employee"> <xsl:for-each select="@name"> <xsl:value-of select="." /> </xsl:for-each>,<xsl:for-each select="@title"> <xsl:value-of select="." /> </xsl:for-each>,<xsl:for-each select="@companyYears"> <xsl:value-of select="." /> </xsl:for-each> <xsl:text> &#xd;&#xa;</xsl:text> </xsl:for-each> </xsl:for-each> </xsl:template> </xsl:stylesheet>

The output from the PersonnelCSV.xsl stylesheet is shown here:


Collapse | Copy Code
Shahab,Customer Service,1 Noosha,Manager,12 Navid,Salesman,3 Mehrdad,CEO,27

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE order SYSTEM "order.dtd"> <order> <orderEntry> <food IMAGE="Burger"/> <price>2.50</price> </orderEntry> <orderEntry> <food IMAGE="Fries"/> <price>1.00</price> </orderEntry> <orderEntry> <food IMAGE="Pie"/> <price>1.50</price> </orderEntry> <orderEntry> <food IMAGE="SoftDrink"/> <price>1.50</price> </orderEntry> <orderEntry> <food IMAGE="Total"/> <price>6.50</price>

</orderEntry> </order> Example 1 -- After !!!


Image Kind Price

Burger

2.50

Fries

1.00

Pie

1.50

SoftDrink

1.50

Total

6.50

111111111111
Whether you use an external or internal DTD, the actual syntax for the DTD is the same - the same code could just as easily be part of an internal DTD or an external one. The only difference between internal and external is in the way it's declared with DOCTYPE. Using an internal DTD, the code is placed between the DOCTYPE tags (i.e. <!DOCTYPE tutorials [ and ]>.

Example Internal DTD

This is an example of an internal DTD. It's internal because the DTD is included in the target XML document:

<?xml version="1.0" standalone="yes"?> <!DOCTYPE tutorials [ <!ELEMENT tutorials (tutorial)+> <!ELEMENT tutorial (name,url)> <!ELEMENT name (#PCDATA)> <!ELEMENT url (#PCDATA)> <!ATTLIST tutorials type CDATA #REQUIRED> ]> <tutorials type="web"> <tutorial> <name>XML Tutorial</name> <url>http://www.quackit.com/xml/tutorial</url> </tutorial> <tutorial> <name>HTML Tutorial</name> <url>http://www.quackit.com/html/tutorial</url> </tutorial> </tutorials>

11111111
An external DTD is one that resides in a separate document. To use the DTD, you need to link to it from your XML document by providing the URI of the DTD file. This URI is typically in the form of a URL. The URL can point to a local file using a relative reference, or a remote one (i.e. using HTTP) using an absolute reference.

Example External DTD


Here's an example of an XML document that uses an external DTD. Note that the "standalone" attribute is set to "no". This is because the document relies on an external resource (the DTD):

<?xml version="1.0" standalone="no"?> <!DOCTYPE tutorials SYSTEM "tutorials.dtd"> <tutorials type="web"> <tutorial> <name>XML Tutorial</name> <url>http://www.quackit.com/xml/tutorial</url> </tutorial> <tutorial> <name>HTML Tutorial</name> <url>http://www.quackit.com/html/tutorial</url> </tutorial> </tutorials>

And, using the above XML document as an example, here's an example of what "tutorials.dtd" (the external DTD file) could look like. Note that the external DTD file doesn't need the DOCTYPE declaration - it is already on the XML file that is using this DTD:

<!ELEMENT <!ELEMENT <!ELEMENT <!ELEMENT <!ATTLIST

tutorials (tutorial)+> tutorial (name,url)> name (#PCDATA)> url (#PCDATA)> tutorials type CDATA #REQUIRED>

1111

XML Tree
Previous Next Chapter
XML documents form a tree structure that starts at "the root" and branches to "the leaves".

An Example XML Document


XML documents use a self-describing and simple syntax:

<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
The first line is the XML declaration. It defines the XML version (1.0) and the encoding used (ISO-8859-1 = Latin-1/West European character set). The next line describes the root element of the document (like saying: "this document is a note"):

<note>
The next 4 lines describe 4 child elements of the root (to, from, heading, and body):

<to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body>

And finally the last line defines the end of the root element:

</note>
You can assume, from this example, that the XML document contains a note to Tove from Jani. Don't you agree that XML is pretty self-descriptive?

XML Documents Form a Tree Structure


XML documents must contain a root element. This element is "the parent" of all other elements. The elements in an XML document form a document tree. The tree starts at the root and branches to the lowest level of the tree. All elements can have sub elements (child elements):

<root> <child> <subchild>.....</subchild> </child> </root>


The terms parent, child, and sibling are used to describe the relationships between elements. Parent elements have children. Children on the same level are called siblings (brothers or sisters). All elements can have text content and attributes (just like in HTML).

Example:

The image above represents one book in the XML below:

<bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
The root element in the example is <bookstore>. All <book> elements in the document are contained within <bookstore>. The <book> element has 4 children: <title>,< author>, <year>, <price>.

11

xml - the tree structure


The great benefit about XML is that the document itself describes the structure of data. If any of you have researched your family history, you have probably come across a family tree. At the top of the tree is some early ancestor and at the bottom of the tree are the latest children. With a tree structure you can see which children belong to which parents, which grandchildren belong to which grandparents and many other relationships. The neat thing about XML is that it also fits nicely into this tree structure, often referred to as an XML Tree. Before you even think about matching up these tree terms with their XML counterparts, it might be helpful to see a real XML document converted into a tree structure. The lemonade.xml document we will be using was created by a particularly enterprising kid to keep inventory of her lemonade stand.

XML Code, lemonade.xml:


<inventory> <drink> <lemonade> <price>$2.50</price>

<amount>20</amount> </lemonade> <pop> <price>$1.50</price> <amount>10</amount> </pop> </drink> <snack> <chips> <price>$4.50</price> <amount>60</amount> </snack> </inventory> </chips>

XML Tree:

As you can see from the XML document, inventory is the root element. When we convert the document over to a tree format, we can see that the inventoryelement is at the top of the tree. In other words, all other elements are a descendent of the inventory element. Construction of an XML tree isn't all that hard to do, as long as you follow some basic rules.

xml tree rules


We've written up a set of rules to use in figuring out if an element is a child or parent of another element. With these basic rules, you can figure out the relationship of just about any two elements in an XML document. Descendants: If element A is contained by element B, then A is a descendant of B. In the lemonade.xml example, every element is a descendant of inventorybecause inventory is the root element. Ancestors: If an element B contains element A, then B is an ancestor of A. In the lemonade.xml example, drink is the ancestor of lemonade and pop.

xml family tree continued

The next few lessons will go into more detail about descendant, ancestor, child, parent and sibling relationships in an XML document. If you are still attempting to grasp the notion of the XML Tree structure, we recommend that you carefully read through each of these lessons.

1111111111111

Web Pages are NOT Created Equal

HTML editors are great for creating web pages quickly and easily. They are a convenienc beginners and experienced web masters alike. But all HTML editors do not write identical some straight HTML editors do a very good job (I'm partial to Arachnophilia), many WYSIW write what we callbloated code, using much more code than is necessary and increasing y download times exponetially. Most experienced web authors avoid using a word processo Microsoft Word/Publisher to create their web pages.

The Mini Web Page illustrated on the right is about as simple as a web page can be. Belo versions of code for this Mini Web Page. In your browser, the pages appear to be virtually but the file size for the MS Word2000 generated web page is 3-1/2 times the size of the ba page. You probably won't notice much difference when visiting this Mini Page. But an ave page containing about 25Kb of HTML requires about 7 seconds to download with a 28.8 m MS Word version of the HTML for the same page will require at least 28 seconds to down

Other things to consider when using a word processor or WYSIWYG editor to generate yo

1. The complexity of the generated code which can make it difficult to find errors, or ed code manually; for example, inserting the snippet of code for a RootsWeb counter; a

2. Proprietary code which may not work in other browsers.

You can view and compare both versions of the Mini Web Page using the actual pagelinks
Basic HTML Code File size=1,015 bytes * See the actual page created by this code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <title> Web Page Code - HTML </title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="author" content="Copyright2000 Patricia J. Asher"> <meta name="keywords" content="HTML,XHTML,tutorial"> <meta name="description" content="HTML vs XHTML, part of a brief tutorial on the basics of writing HTML."> </head> <body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000"> <h1 align="center"> This is a Mini Web Page </h1> <p align="center"> It includes all the basic components of any web page: <br> META tags and some links: <br> See the <a href= "http://homepages.rootsweb.ancestry.com /~pasher/wpcode/xhtmlvers.htm"> XHTML Version </a> <br> Back to <a href= "http://freepages.computers. rootsweb.ancestry.com /~pasher/wpcode.htm"> <i> Web Pages are NOT Created Equal </i> </a> </p> <p align="center"> And a graphic: <img src="rweb1.gif" width="170" height="60" alt="RootsWeb"> </p> <br> <br> </body> </html>

XHTML Code written by MSWord File size=3,436 bytes * See the actual page created by this

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1 Transitional//EN"> <html xmlns:v="urn:sche microsoft-com:vml" xmlns:o="urn:schemasmicrosoft-com:office:office" xmlns:w="urn: microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"> < http-equiv=Content-Type content="text/html charset=iso-8859-1"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Wo name=Originator content="Microsoft Word 9" rel=File-List href="./xhtmlvers_files/file <link rel=Edit-Time-Data href="./xhtmlvers_files/editdata.mso"> <!--[if !mso]> <style> v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} </style> <![endif]--> <title> Web Page Code - XHTML <!--[if gte mso 9]> <xml> <o:DocumentProperties> <o:Author>Patricia Asher</o:Author> <o:LastAuthor>Patricia Asher</o:LastAuthor> <o:Revision>2</o:Revi <o:TotalTime>4</o:TotalTime> <o:Created>20 12T20:20:00Z</o:Created> <o:LastSaved>2002 12T20:20:00Z</o:LastSaved> <o:Pages>1</o:P <o:Words>63</o:Words> <o:Characters>362</o <o:Lines>3</o:Lines> <o:Paragraphs> 1 </o:Paragraphs> <o:CharactersWithSpaces> 4 </o:CharactersWithSpaces> <o:Version>9.3821</o:Version> </o:Document </xml><![endif]--> <style> <!-- /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; marginbottom:.0001pt; mso-pagination:widow-orpha size:12.0pt; font-family:"Times New Roman" fareast-font-family:"Times New Roman"; col h1 {color:black;} a:link, span.MsoHyperlin {color:blue; text-decoration:underline; te underline:single;} a:visited, span.MsoHyperlinkFollowed {color:purple; t decoration:underline; text-underline:singl size:12.0pt; font-family:"Times New Roman" fareast-font-family:"Times New Roman"; col @page Section1 {size:8.5in 11.0in; margin: 1.0in 1.25in; mso-header-margin:.5in; msomargin:.5in; mso-paper-source:0;} div.Sect

{page:Section1;} --> </style> <!--[if gte <o:shapedefaults v:ext="edit" spidmax="102 </xml><![endif]--><!--[if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ex data="1"/> </o:shapelayout></xml><![endif] name=author content="Copyright2000 Patrici <meta name=keywords content="HTML,XHTML,tu <meta name=description content="HTML vs XH part of a brief tutorial on the basics of writing HTML."> </head> <body bgcolor=w lang=EN-US link=blue vlink=purple style='t interval:.5in' alink="#ff0000"> <div class <h1 align=center style='text-align:center' Mini Web Page </h1> <p align=center style= align:center'>It includes all the basic co any web page: <br> META tags and some link the <a href= "http://homepages.rootsweb.ancestry.com /~pasher/wpcode/htmlvers.htm"> HTML Versio Back to <a href= "http://freepages.computers.rootsweb.com /~pasher/wpcode.htm"> <i> Web Pages are NO Equal </i> </a> </p> <p align=center style align:center'>And a graphic: <img border=0 height=60 id="_x0000_i1025" src=rweb1.gif alt=RootsWeb></p> <p class=MsoNormal style bottom:12.0pt'> <![if !supportEmptyParas]> [endif]><o:p></o:p></p> </div> </body> </h

* Note: File size refers to the HTML only and does not include the graphic displayed on th Page.

Das könnte Ihnen auch gefallen