Saturday, March 31, 2012

XML


XML stands for eXtensible Markup Language and it was designed to transport and store data. XML does not replace HTML. XML does not DO anything but it structures data, stores and transports data. The code below just stores the information of this note. But it does not do anything with it.


01
<note>
02
<to>Daniel</to>
03
<from>Mark</from>
04
<heading>Reminder</heading>
05
<body>Don't forget me!</body>
06
</note>

History of XML

Experienced SGML and WWW users realized that technologies available could pose some serious problems. SGML was added to the W3C (World Wide Web Consortium) in 1995 and work began on a new standard.

XML was built by a working group of 11 members and an interest group of 150 members. The project had 3 editors and XML was designed using emails and teleconferences. 20 weeks later, the first working draft was released. W3C recommended XML 1 in early 1998. XML 1.0 achieved the following list of goals:

  • internet usability
  • SGML compatibility
  • general purpose stability
  • formality
  • conciseness
  • legibility
  • ease of authoring
  • minimization of optional features


The fourth edition of XML was released on the 16th of August, in 2006.
[http://www.totalxml.net]


Why XML?

Several reasons exist for using XML. Among these we find the following:

Self describing data
Business applications have several tasks apart from presenting the content. XML is ideal here because it offers complete data usability and also proper presentation of data. XML is preferred over traditional database systems.

Integration of traditional databases and formats
XML documents supports all types of data such as text and numbers, multimedia, sound and video and also active formats such as Java Applets and Active X components.

Data presentation modifications
XML Style Sheets can be used in a similar way as CSS. The can modify documents and websites while keeping the same data.

One Server View
An XML document can contain data from multiple servers and different databases. This means that the whole WWW is converted into one database.

Internationalization
XML supports documents with more than one language and Unicode standards are also supported. This is of utmost importance in electronic business applications

Open and extensible
The XML structure can be modified to match specific vocabulary and users can opt to add elements if they need them.

Used to create new Internet Languages
Several Internet Languages were created with XML. These include: XHTML, WSDL, WAP, WML, RSS, and more.

Syntax of XML

The first line of an XML document is the XML Declaration which defines the XML version and encoding used. Next up is the declaration of the root element. There can be only one root element in the XML document. This is known as the Tree Structure of XML and can be seen in the example below:


01
<inventory>
02
<drink>
03
<lemonade>
04
<price>$2.50</price>
05
<amount>20</amount>
06
</lemonade>
07
<pop>
08
<price>$1.50</price>
09
<amount>10</amount>
10
</pop>
11
</drink>
12
<snack>
13
<chips>
14
<price>$4.50</price>
15
<amount>60</amount>
16
</chips>
17
</snack>
18
</inventory>

Figure 1: The tree structure represented in the XML code above

Rules in XML are very simple and logical. All elements must have a closing tag. Unlike HTML, XML does not compile if the closing tag is missing. XML Tags are also case sensitive. This means that <name> is not the same as <Name>. This makes XML faster. XML Elements must be properly nested. An element which is opened within another element must be closed within that element.  The XML document must have a root (or parent) element. XML elements can have attributes and the attribute values must be quoted. This is shown in the code snippet below:

<person birthdate="12/11/1998">

The < and the & are illegal characters in XML. This makes comparisons different from other languages. Although the > character is perfectly legal, it is still recommended to use the predefined entry references in XML. This can be seen in the table below:

&lt;
< 
less than
&gt;
> 
greater than
&amp;
&
ampersand
&apos;
'
apostrophe
&quot;
"
quotation mark
Table 1: Entry References in XML

Comments in XML have a slightly different syntax and these are shown as below:

<!-- This is a comment -->

Criticism of XML

XML, together with its extensions have been regularly criticized for complexity and verbosity. XML can be difficult to use when mapping the basic tree model of XML to type systems of programming languages or databases. This is more difficult when used to exchange data between applications which is highly structured since this was not the primary design goal. Alternatives to XML are JSON and YAML as they both focus on representing structured data instead of narrative documents.

XPath

XPath is a syntax for defining parts of an XML document. It uses expressions to navigate in XML documents. It also contains a library of standard functions and it is a major element in XSLT. It includes more than a hundred built-in functions.

In XPath, there are seven types of nodes. These are element, attribute, text, namespace, processing-instruction, comments and document nodes. XML documents are considered to be trees of nodes. The root element is at topmost element of the tree. XPath is used to query the XML document to obtain the needed the information. It can be used to search for items with particular name, and also by making comparisons. Wild cards can also be used.

XSL and XSLT

XSL is made up of three parts: XSLT, XPath and XSL-FO. XSLT stands for eXtensible Stylesheet Language Transformations and is a language for transforming XML document. XSL-FO is a language for formatting XML documents.

XSLT is used to transform XML document into another XML document, or to another type of document such as HTML or XHTML. XSLT uses XPath to find information in an XML document and then is transforms the matching parts into the result document.

A small example will incorporate XML, XSL and XPath.

CD Collection Example

First we start by having a collection of CDs information inside an XML document. This document will hold the title, the artist, the country, the company, the price and the year of issue. We also add the reference to the style sheet after the declaration of XML version. A sample of the document can be seen below:


01
<?xml version="1.0" encoding="ISO-8859-1"?>
02
<?xml-stylesheet type="text/xsl" href="s.xsl"?>
03
<catalog>
04
     <cd>
05
           <title>Empire Burlesque</title>
06
           <artist>Bob Dylan</artist>
07
           <country>USA</country>
08
           <company>Columbia</company>
09
           <price>10.90</price>
10
           <year>1985</year>
11
     </cd>
12
     <cd>
13
           <title>Hide your heart</title>
14
           <artist>Bonnie Tyler</artist>
15
           <country>UK</country>
16
           <company>CBS Records</company>
17
           <price>9.90</price>
18
           <year>1988</year>
19
</cd>
20
</catalog>

Then we create the style sheet in another XSL document. In this style sheet we create a table with 6 columns to display all the information of each CD. Using a for-each loop and XPath to find each instance of CD, we put the value of the title and of the artist in each column of the new row.


01
<?xml version="1.0" encoding="ISO-8859-1"?>
02
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
03
<xsl:template match="/">
04
  <html>
05
  <body>
06
  <h2>My CD Collection</h2>
07
    <table border="1">
08
      <tr bgcolor="#9acd32">
09
        <th>Title</th>
10
        <th>Artist</th>
11
      </tr>
12
      <xsl:for-each select="catalog/cd">
13
      <tr>
14
        <td><xsl:value-of select="title"/></td>
15
        <td><xsl:value-of select="artist"/></td>
16
      </tr>
17
      </xsl:for-each>
18
    </table>
19
  </body>
20
  </html>
21
</xsl:template>
22
</xsl:stylesheet>

When the XML document is opened in a browser the style is very different and it is much easier to read the required information. The final result can be seen below:


Figure 2: The final result of the XML document with XSL

Monday, March 26, 2012

JavaScript and OOP


Following the introductory blog about JavaScript, I am now evolving more into JavaScript in relation to object oriented programming. JavaScript supports Object Oriented Programming because it supports inheritance through prototypes, properties and methods. Some people do not realize that JavaScript supports inheritance. JavaScript syntax is similar to the syntax of Java and C#. The fact that JavaScript supports inheritance and thus making it an Object Oriented Language, gives the developers of JavaScript power. Code can be written once and be used again, while supporting encapsulation.

Why are objects great?

Objects created in JavaScript act like real life objects and they have properties and methods. People, animals, cars and furniture all have properties. Properties of human beings are height, for example with a value of 160cm. Methods of people can be speaking or running. Methods can also change properties, such as eating and gaining weight.

JavaScript enables developers to create their own objects for their applications. Objects allow programmers to code events that respond to actions by the end user. Objects can be initialized any number of times, and also with different values.

Creating objects using the new operator

There are two ways to create objects in JavaScript. One of the most common methods is to use the new operator. The syntax for this is to use the new Object(); piece of code.    This works by first declaring the new Object, and then adding the properties to this object.

01
person = new Object();
02
person.name = “Daniel”;
03
person.surname = “Borg”;
04
person.age = 24;

The code snippet above show a new person object being created and then the properties name, surname and age are created and assigned a value. Apart from properties we can also create methods assigned to that object. This can be seen in the code snippet below:

05
person.talk = function () {
06
     this.state = “talking”;
07
     this.volume = “high”;
08
}

Above we can see that a person can do a method talk and during that method he will be talking with high volume. However, this is not the only way to create an object.

Creating objects using the literal notation

Another way is to create the object in literal notation. This feature is supported from version 1.2 onwards. It is more robust and can be easier to create an object on the fly using this method. As an example we can create the same object but using literal notation.

01
person = {
02
     name: “Daniel”,
03
     surname: “Borg”,
04
     age: “24”,
05
     talk: function () {this.state = “talking”}
06
};

This code above is exactly the same as the previous code but in literal notation. However, both examples here cannot be reused.

Object Constructor and Prototyping

The best way to create an object would be to use the Object Constructor Function. The object constructor is very robust since it is a JavaScript function. It can define parameters and call other functions, amongst other features. The difference between the other method and the method using constructor is that a constructor function is called via the new operator. Now I will create a function used as an object constructor. The properties and methods of the object are declared within this function by using the prefix this.  New objects are created using the object constructor by using the new keyword. Using this method we can create multiple objects.

01
function dog(name) {
02
     this.name = name;
03
     this.talk = function () {
04
          alert(this.name + “ said Woof!!”;
05
     }
06
};
07
dog1 = new dog(“Aslan”);
08
dog1.talk();
09
dog2 = new dog(“Butch”);
10
dog2.talk();

The code above shows the same object constructor used to create two different objects with the same code.

Prototyping

Prototyping is a more elegant approach to add a method to the constructor function. It is a type of inheritance in JavaScript. Prototyping can be described by a particular race learning a particular method and then all members of that race will be able to use that method.

01
dog.prototype.changeName = function(name) {
02
     this.name = name;
03
}

The code above adds the method changeName to all instance of a dog. Using the code below will generate “Snowy said Woof!!” instead of “Aslan said Woof!!”.

01
dog1.changeName(“Snowy”);
02
dog1.talk();

This shows that after that method was added, all instances of dog were able to use that method.

Sub and Super Classes

We already saw that JavaScript supports prototype inheritance. However, C# and Java contain an explicit concept of class hierarchy in the sense that every class can have both a super class and a sub class. The super class is from where the class inherits the properties and the methods. On the other hand, a class can be extended to other subclasses which inherit the methods and properties from the parent’s behaviour. JavaScript prefers to use prototype but it is still possible for inheritance to take place in other ways.
The example below shows this more clearly.

01
function superClass() {
02
     this.supertest = superTest;
03
}
04
function subClass() {
05
     this.inheritFrom = superClass;
06
     this.inheritFrom();
07
     this.subtest = subTest;
08
}
09
function subtest() {
10
     return “SuperTest”;
11
}
12
var newClass = new subClass();
13
alert(newClass.subtest());
14
alert(newClass.supertest());

Here we created two classes, superClass and subClass. superTest() was attached to the superClass while subTest() was attached to subClass. Line 05 states that the subClass should inherit from the superClass. To test this out, two alerts were created, both calling methods from the instance of the subClass. However, the second alert is calling a function which is written within the code of the superClass. This is available to the subClass through inheritance from the superClass.

Now we have a better understanding of how objects work in JavaScript and how we can use objects to help us write less code to achieve more results.