xml internet engineering spring 2014 bahador bakhshi ce & it department, amirkabir university of...

83
XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Upload: wilfred-spencer

Post on 22-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML

Internet Engineering

Spring 2014

Bahador Bakhshi

CE & IT Department, Amirkabir University of Technology

Page 2: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

QuestionsQ6) How to define the data that is transferred

between web server and client?Q6.1) Which technology?Q6.2) Is data correctly encoded?Q6.3) How to access the data in web pages?Q6.4) How to present the data?

2

Page 3: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

HomeworkHomework 3

Will be announced

3

Page 4: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

OutlineIntroductionNamespacesValidationPresentationXML Processing (using JavaScript)Conclusion

4

Page 5: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

OutlineIntroductionNamespacesValidationPresentationXML Processing (using JavaScript)Conclusion

5

Page 6: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

IntroductionHTML + CSS + JavaScript Dynamic Web pages

Web server is not involved after page is loaded JavaScript reacts to user events

However, most web applications needs data from server after the page is loaded e.g., new emails data in Gmail A mechanism to communication: AJAX A common (standard) format to exchange data

In most applications, the data is structured 6

Page 7: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Introduction (cont’d)In general (not only in web) to store or

transport data, we need a common format, to specify the stucture of data; e.g., Documents: PDF, HTML, DOCx, PPTx, ... Objects: Java Object Serialization/Deserialization

How to define the data structure? Binary format (similar to binary files)

Difficult to develop & debug, machine depended, … Text format (similar to text files)

Human readable, machine independent & easier7

Page 8: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Introduction (cont’d) Example: Data structure of a class

Course name, teacher, # of students, each student information

8

IEBakhshi48AliHassani1111BabakHosseini2222….

Student num: 48Name: IETeacher: BakhshiAli Hassani 1111Babak Hosseini 2222….

class Course{ string name; string teacher; integer num; Array st of Students;}

c = new Course();c.name = IE;c.teacher = Bakhshi;c.num = 48st[1] = new Student();st[1].name=Ali; st[2].fam=Hassani….

Page 9: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Introduction (cont’d)W3C approach

XML: eXtensible Markup Language A meta-markup language to describe data structure

In each application, a markup language (set of tags & attributes) are defined using XML

9

<course> <title> IE </title> <num> 48 </num> <teacher> Bakhshi </teacher> <students> <student><name>Ali</name> <fam>Hassani</fam> <id> 1111 </id></student> … </students></course>

Page 10: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Introduction (cont’d)Standard Generalized Markup Language (SGML)

Expensive, complex to implement

XML: a subset of SGML Goals: simplicity, generality, and usability Simplifies SGML by:

leaving out many syntactical options and variants SGML ~ 600pp, XML ~ 30pp XML = SGML {complexity, document perspective}

+ {simplicity, data exchange perspective}

10

Page 11: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Why to Study XML: BenefitsSimplify data sharing & transport

XML is text based and platform independent

Extensive tools to process XML To validate, to present, to search, …

In web application, data separation from HTML E.g., table structure by HTML, table data by XML

Extensible for different applications A powerful tool to model/describe complex data E.g., MS Office!!!

11

Page 12: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Document ElementsMarkup

Elements Tag + Content Attributes

Comments Processing instructions

Content Parsed Character Data Unparsed Character Data (CDATA)

12

Page 13: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML ElementsXML element structure

Tag + content

<tagname attribute=“value”> Content

</tagname>No predefined tagIf content is not CDATA, is parsed by parser

A value for this element Child elements of this element

13

Page 14: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Elements’ Attributes Tags (elements) are customize by attribute

No predefined attributes

<os install="factory">Windows</os>

<os install="user">Linux</os>

Attribute vs. Tags (elements) Attributes can be replaced by elements

Attribute cannot be repeated for an element Attribute cannot have children

Attributes mainly used for metadata, e.g., ID, class

14

Page 15: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Processing Instructions Processing instructions pass information (instruction) to

the application that process the XML file They are not a part of user data

<?Target String ?>

Common usage<?xml-stylesheet href="URL" type="text/xsl"?>

XML Declaration is a special PI<?xml version="1.0" encoding="UTF-16"?> XML Declaration is always first line in file

15

Page 16: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Basic XML Document Structure<?xml version="1.0" encoding="UTF-16"?>

<root-tag>

<inner-tags>

Data

</inner-tags>

<!-- Comment -->

</root-tag>

16

Page 17: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Example <?xml version="1.1" encoding="UTF-8" ?> <notebook><name>ThinkPad</name><model>T500</model><spec><hardware>

<RAM>4GB</RAM></hardware><software>

<OS>Linux, FC20 </OS></software>

</spec></notebook>

17

Page 18: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Example (CDATA) <?xml version="1.1" encoding="UTF-8" ?> <operator><mathematic>

+ - * / %</mathematic><comparison>

<![CDATA[< <= == >= > !=

]]></comparison>

</operator>18

Page 19: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML vs. HTMLTags

HTML: Predefined fixed tags XML: No predefined (meta-language)

User defined tags & attributes

Purpose HTML: Information display XML: Data structure & transfer

Rules’ strictness HTML (not XHTLM): loose XML: strong/strict rule checking

19

Page 20: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML in General Application XML by itself does not do

anything XML just describes the

structure of the data Other applications parse

XML and use it

A similar approach is used for formats (event user-defined format); so, what is the advantages of XML?!!! XML is standard Available XML tools & technologies

20

XML document

XML processor

(aka. XML Parser)

application

SAX, DOM

Apache Xerces

Page 21: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Technology Components Data structure (tree) representation

XML document (a text file)

Validation & Conformance Document Type Definition (DTD) or XML Schema

Element access & addressing XPath, DOM

Display and transformation XSLT or CSS

Programming, Database, Query, …21

Page 22: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

OutlineIntroductionNamespacesValidationPresentationXML Processing (using JavaScript)Conclusion

22

Page 23: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Namespaces In XML, element names are defined by developers

Results in a conflict when trying to mix XML documents from different XML applications

XML file 1<table>

<tr><td>Apples</td> <td>Bananas</td>

</tr></table>

XML file 2<table>

<name>Dinner Table</name><width>80</width> <length>120</length>

</table>

23

Page 24: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Namespaces Name conflicts in XML can easily be avoided by

using a qualified names according to a prefix Prefix is the namespaces Qualified name is the prefixed name

Step 1: Namespace declaration Defines a label (prefix) for the namespace and

associates it to the namespace identifier URI/URL is used to be universally unique

Step 2: Qualified name namespace prefix: local name

24

Page 25: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Namespaces <?xml version="1.0"?> <ceit:course xmlns:ceit="http://ceit.aut.ac.ir"> <ceit:department> <ceit:name> Computer Engineering & Information Technology </ceit:name></ceit:department><ceit:name>

Internet Engineering</ceit:name>

</ceit:course>25

Actual name of this tag of parser: http://ceit.aut.ac.ir:department

Page 26: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Default Namespaces <alltables><table xmlns="http://www.w3.org/TR/html4/"><tr>

<td>Apples</td> <td>Bananas</td></tr>

</table>

<table xmlns="http://www.dinnertable.com"><name>Dinner Table</name><width>80</width><length>120</length>

</table></alltables>

26

Page 27: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

OutlineIntroductionNamespacesValidationPresentationXML Processing (using JavaScript)Conclusion

27

Page 28: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Valid XMLXML is used to describe a structured data

The description must be correct A valid XML file

Correctness Syntax

Syntax error parser fails to parse the file Syntax rules: e.g., all XML tags must be closed

Symantec (structure) Application specific rules, e.g. student must have ID Error Application failure

28

Page 29: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Syntax Rules (Well-Formed) Start-tag and End-tag, or self-closing tag Tags can’t overlap XML documents can have only one root element XML naming conventions

Names can start with letters or the dash (-) character After the first character, numbers, hyphens, and periods are allowed

Names can’t start with “xml”, in uppercase or lowercase There can’t be a space after the opening < character XML is case sensitive Value of attributes must be quoted White-spaces are preserved

&, <, > are represented by &amp; &lt; &gt;

29

Page 30: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

How to Validate XML?1) Application specific programs need to check

structure of XML document Different applications different programs Change in data structure code modification

2) General XML parser + reference document Reference document

Tag names, attributes, tree structure, tag relations, … Different reference documents

DTD, XML Schema, RELAX NG

30

Page 31: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Validation (cont’d)Document Type Definition (DTD) or XML Schema

A language to define document type The rules of the structure of XML

Internal or External

31

XML dataparser

parserinterface

XML-basedapplication

DTD / Schema

Page 32: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

DTDDTD is a set of structural rules called declarations,

specify A set of elements and attributes that can be in XML

Where these elements and attributes may appear <!keyword …>

ELEMENT: to define tags For leaf nodes: Character pattern For internal nodes: List of children

ATTLIST: to define tag attributes Includes: name of the element, the attribute’s name, its

type, and a default option

32

Page 33: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

ELEMENT Declaration General form of internal nodes

<!ELEMENT element_name (list of children)> To control the number of times a child may appear

+ : One or more * : Zero or more ? : Zero or one

General form of leaf nodes <!ELEMENT element_name (#type)> Where, types

PCDATA: Most commonly used, the content will be parsed, i.e. < > & is not allowed

ANY: Any character can be used EMPTY: No content

33

Page 34: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

ATTLIST Declaration <!ATTLIST element_name attribute_name

attribute_type default_option> element_name: The name of the corresponding element attribute_name: The name of attribute attribute_type: Commonly CDATA is used default_option:

A value: The default value of the attribute #REQUIRED: The attribute is mandatory

34

Page 35: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Example: Internal DTD<?xml version="1.0"?><!DOCTYPE name [<!ELEMENT name (first, middle, last)><!ATTLIST name nickename (#CDATA)><!ELEMENT first (#PCDATA)><!ELEMENT middle (#PCDATA)><!ELEMENT last (#PCDATA)>]><name nickname="Jo"> <first>John</first> <middle>Johansen</middle> <last>Smith</last></name>

35

Page 36: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

External DTD System<!DOCTYPE root_name SYSTEM "URL" >

Public<!DOCTYPE root_name PUBLIC "-//name//DTD

Name//EN" "URL"> Common format is FPI (Defined in the document ISO 9070)

Example<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

36

Page 37: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Example: External DTDsample.dtd<!ELEMENT note (to+,from,heading*,main)><!ELEMENT to (#PCDATA)><!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)><!ELEMENT main (#PCDATA)>--------------------------------------------------------------------------external-dtd.xml<?xml version="1.0" ?> <!DOCTYPE note SYSTEM "sample.dtd" ><note>

<to>Ali</to> <to>Hassan</to> <from>Babak</from> <main>This is message</main>

</note>

37

Page 38: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Schema XML Schema describes the structure of an XML file

Also referred to as XML Schema Definition (XSD)

XML Schemas benefits (DTD disadvantages) Created using basic XML syntax (DTD has its own syntax) Validate text element content based on built-in and user-defined

data types (DTD does not fully support data type)

Similar to OOP Schema is a class & XML files are instances Schema specifies

Elements and attributes, where and how often Data type of every element and attribute

38

Page 39: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Schema (cont’d)XML schema is itself a XML-based language

Has its own predefined tags & namespacexmlns:xs="http://www.w3.org/2001/XMLSchema"

Two categories of data types Simple: Cannot have attribute or nested elements

Primitive: string, Boolean, integer, float, ... Derived: byte, long, unsignedInt, … User defined: restriction of base types

Complex: Can have attribute or/and nested elements

39

Page 40: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Schema (cont’d) Simple element declaration

<xs:element name="a name" type="a type" />

Complex element declaration<xs:element name="a name"> <xs:complexType> <xs:sequence> or <xs:all> <xs:element name minOccures="…" maxOccures="…"/> </xs:sequence> or </xs:all> </xs:complexType></xs:element>

40

Page 41: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Schema Example: note.xsd<?xml version="1.0"?><xs:schema

xmlns:xs="http://www.w3.org/2001/XMLSchema"><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="date" type="xs:date"/> </xs:sequence>

</xs:complexType> </xs:element> </xs:schema>

41

Page 42: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Schema Example: note.xml<?xml version="1.0"?><note xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="note.xsd">

<to>Ali</to> <from>Reza</from> <date>1391/1/1 </date>

</note>

42

Page 43: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Validation ToolsOnline validators

validator.w3.org www.xmlvalidation.com

XML tools & commands xmllint commands in Linux

xmllint xmlfile --valid --dtdvalid DTD xmllint xmlfile --schema schema

XML libraries LibXML2 for C Java & C# XML libraries

43

Page 44: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

OutlineIntroductionNamespacesValidationPresentationXML Processing (using JavaScript)Conclusion

44

Page 45: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML PresentationBy default, browsers parses & displays XML files

Tree structure of XML Syntax checking Well-formed XML

Other presentations of XML 1) Browsers support CSS for XML files

CSS is used to format the representation of XML 2) Transform to HTML + CSS using XSLT

A powerful tool to separate data from HTML 3) Use JavaScript to generate HTML for XML

Parse the XML and create HTML elements

45

Page 46: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML & CSSAttach styling instructions directly to XML <?xml-stylesheet href="URL" type="text/css" ?>

Can style but not rearrange elements Block or inline style Bold, italic, underline, font, color, etc. …

Tag_name {color:red; font-weight:bold; font-family:serif;}

46

Page 47: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

CSS Example <?xml version="1.0" encoding="UTF-8"?>

<programming>Good programming books:<C> <book>

<title>The C Programming Language </title><author>Ritchie</author>

</book></C><Java> <book>

<title>Thinking in Java </title><author>Eckel</author>

</book></Java>

</programming>==========================================

*{display: block;}programming{font-family: Arial; font-size:20pt;}C{color: blue;}Java{color: green;}author{ font-style:italic;}

47

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

Page 48: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML & CSSCSS is mainly designed to format HTML

presentationIt does not work well in XML

XML does not have any predefined tags/attributes No ID, No Class

CSS for XML uses tag names The same style for all tags with the same name

CSS can only present the data in XML Cannot process & transform the data into other format e.g., presenting data as a table

48

Page 49: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLXSL stands for eXtensible Stylesheet Language,

and is a style sheet language for XML documents Started with XSL & leads to XSLT, XPath, and XSL-FO

Xpath A language for navigating XML documents

XSLT (XSL Transform) Transforms XML into other formats, like HTML

XSL-FO (XSL Formatting Objects) Not discussed here!

49

Page 50: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XPathXPath is a language for addressing different

parts of XML document XPath is a syntax for defining parts of an XML

XPath uses path expressions to navigate in XML documents

50

Page 51: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XPath: Basic SyntaxXPath considers the tree structure of XML

Parent, child, sibling, Ancestor, … Very similar to Linux FS hierarchy

Nodes are selected using path expressions Absolute path: starts with / Relative path: starts with a node name

Levels are separated by / Expressions can be based on attributes

51

Page 52: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XPath: Basic Syntax (cont’d)

Expression Description

/ Selects from the root node

// Selects nodes from descendants of the current node

. Selects the current node

.. Selects the parent of the current node

@ Selects attributes

* Matches any element node

@* Matches any attribute node

52

Page 53: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XPath: Basic Syntax: Example<bookstore>

<book><title lang="eng">Beginning XML</title> <price>100</price>

</book></bookstore>

53

Path Expression Result/bookstore Selects the root element bookstorebookstore/book Selects all book elements that are children of bookstorebookstore/book/title Selects titles of all books//book Selects all book elements no matter where they are in the

documentbookstore//book Selects all book elements that are descendant of the

bookstore element, no matter where they are under the bookstore element

//@lang Selects all attributes that are named lang

Page 54: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XPath: Advanced SyntaxPath Expression Result

/bookstore/book[1] Selects the first book element that is the child of the bookstore element.

/bookstore/book[last()] Selects the last book element that is the child of the bookstore element

/bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore element

/bookstore/book[position()<3] Selects the first two book elements that are children of the bookstore element

//title[@lang] Selects all the title elements that have an attribute named lang

//title[@lang='eng'] Selects all the title elements that have an attribute named lang with a value of 'eng'

/bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00

54

Page 55: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLTWhat is XSLT (XSL Transformations)?

XSLT is a XML file that transforms an XML document into another document: e.g., XML or XHTML

How does it work? XSLT is composed of templates

XSLT uses XPath to define parts of XML that should match template Algorithm:

Set current node = / Find the (best) template that match the current node If matched (current node == Path expression), transform current node

into the result document defined by XSLT commands in the template If not matched, apply the default template

55

Applying Templates

Page 56: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Structure<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="expression">

HTML tags + XSLT commands

Other contents

</xsl:template>

</xsl:stylesheet>

56

The “HTML tags and XSLT commands” are run for each node that is matched to the given “expression”

The default template: If there is a child node current node = child If there is not child node print the value

Copied to output

Page 57: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Commands (elements)<xsl:output method="method" />

To define the format of the output created by the stylesheet Method (in this course, we want to create HTML from XML)

html or xml

<xsl:template match="expression"> To define a template for a specified nodes

<xsl:apply-templates select="expression"> If select is not given current node = this node and apply

templates If select is given current node = selected nodes and apply

templates

57

Page 58: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Commands (elements) <xsl:value-of select="expression"/>

The value of the specified nodes

<xsl:text disable-output-escaping="yes|no"> Text </xsl:text> Copy the given text to the output If escaping is not disabled output is escaped; i.e, “>” “&gt;”

<xsl:for-each select="expression"> Create a loop on array of selected nodes

<xsl:if test="expression"> Conditional rules

Comparison Operators Equal: = Not equal: != Less than: &lt; Greater than: &gt;

58

Page 59: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Commands (elements) <xsl:choose>

<xsl:when test="expression">

<xsl:otherwise>

</xsl:choose> Switch-case (if-else) rules

The “template applying” algorithm selects the best matched template if current node matches with multiple templates The best is defined according to the priority of templates

The priorities are defined in the standard (we don’t see here) E.g., in the case of multiple template with identical match attribute,

the last template has the highest priority

59

Page 60: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Example: XML Data file<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="xslt-test.xslt"?><class>

<course><name>Internet Engineering</name><semester>Spring 2014</semester>

</course><student>

<name>Ali</name><family>Alizadeh</family><grade>18.0</grade><number>123</number>

</student><student>

<name>Babak</name><family>Babaki</family><grade>7.0</grade><number>234</number>

</student><student>

<name>Hassan</name><family>Hassani</family><grade>19.0</grade><number>345</number>

</student></class>

60

Page 61: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Example: XSLT file<?xml version="1.0" encoding="ISO-8859-1"?><xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"> <html> <body> <h2>Course: <xsl:value-of

select="/class/course/name"/></h2> <h3>Semester: <xsl:value-of select="//semester"/>

</h3><h3>Students: <xsl:for-each select="//family"> "<xsl:value-of select="."/>" </xsl:for-each></h3>

<table border="1"> <tr> <th> Student # </th> <th>Name</th>

<th>Family</th> <th>Grade</th></tr>61

Page 62: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

62

<xsl:for-each select="/class/student"> <tr>

<td><xsl:value-of select="number"/></td><td><xsl:value-of select="name"/></td><td><xsl:value-of select="family"/></td>

<xsl:choose> <xsl:when test="grade &lt; 10"> <td style="background-color:red"><xsl:value-of select="grade"/></td> </xsl:when> <xsl:otherwise> <td style="background-color:green"><xsl:value-of select="grade"/></td> </xsl:otherwise> </xsl:choose> </tr></xsl:for-each></table>

</body> </html> </xsl:template></xsl:stylesheet>

Page 63: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Example: Result

63

Page 64: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Example: apply-templates (1)<?xml version="1.0" encoding="ISO-8859-1"?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="html" />

<xsl:template match="/"><html> <body>

<xsl:apply-templates /></body> </html></xsl:template>

<xsl:template match="class"><b><xsl:apply-templates /></b>

</xsl:template>

<xsl:template match="student"> <br /> <em><xsl:apply-templates /></em>

</xsl:template></xsl:stylesheet>

64

Page 65: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Example: apply-templates (2)<?xml version="1.0" encoding="ISO-8859-1"?><xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="html" />

<xsl:template match="/"><html> <body>

<xsl:apply-templates select="/class/course" /><table border="1"> <tr> <th> Student # </th> <th>Name</th> <th>Family</th>

<th>Grade</th></tr> <xsl:apply-templates select="/class/student" /></table>

</body> </html> </xsl:template>

65

Page 66: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Example: apply-templates (2)<xsl:template match="course"> <h2>Course: <xsl:value-of

select="/class/course/name"/></h2> <h3>Semester: <xsl:value-of select="//semester"/>

</h3><h3>Students: <xsl:for-each select="//family"> "<xsl:value-of select="."/>" </xsl:for-each></h3>

</xsl:template>

<xsl:template match="student"> <tr>

<td><xsl:value-of select="number"/></td><td><xsl:value-of select="name"/></td><td><xsl:value-of select="family"/></td>

66

Page 67: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Example: apply-templates (2)<xsl:choose><xsl:when test="grade &lt; 10">

<td style="background-color:red"><xsl:value-of select="grade"/>

</td> </xsl:when> <xsl:otherwise>

<td style="background-color:green"><xsl:value-of select="grade"/>

</td> </xsl:otherwise> </xsl:choose> </tr></xsl:template></xsl:stylesheet>

67

Page 68: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XSLT Example: xsl:text<xsl:template match="student"><tr>

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

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

<xsl:text disable-output-escaping="yes"> &lt;td </xsl:text>

<xsl:choose> <xsl:when test="grade &lt; 10">

<xsl:text disable-output-escaping="yes"> style="background-color:red"&gt; </xsl:text>

</xsl:when> <xsl:otherwise>

<xsl:text disable-output-escaping="yes"> style="background-color:green"&gt; </xsl:text>

</xsl:otherwise> </xsl:choose>

<xsl:value-of select="grade"/><xsl:text disable-output-escaping="yes"> &lt;/td&gt; </xsl:text>

</tr></xsl:template></xsl:stylesheet>

68

Page 69: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Where XSLT?Client-side (browser)

Reduce the load on your serversServer-side

Performance could be a problem on busy servers

Offline Pre-conversion E.g. xsltproc command Linux Best performance Not good for dynamic documents

69

Page 70: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Where XSLT? (cont’d)

70

XSLT

Server transforms to HTML/CSS; Ship to client browser for display

httpHTML+CSS

Browser/Interface

Very common current strategy;Leverages current technology

XML

Stylesheet

Page 71: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

OutlineIntroductionNamespacesValidationPresentationXML Processing (using JavaScript)Conclusion

71

Page 72: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Processor: ParsersThere are two basic types of XML parsers:Tree (DOM)-based parser:

Whole document is analyzed to create a DOM tree Advantages: Multiple & Random access to elements,

easier to validate the structure of XML

Event-based parser (SAX): XML document is interpreted as a series of events When a specific event occurs, a function is called to

handle it (we will see later) Advantages: less memory and faster

72

Page 73: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML Parsing in Browser Web browsers have built-in XML parser

XML parser output: XML DOM

XML DOM is accessible through JavaScriptHow to get XML file in web page (HTML)?

Using AJAX We will see later

(Input) string

73

Page 74: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML DOM XML DOM is similar to HTML DOM

A tree of nodes Nodes are accessed by getElementsByTagName Nodes have value and attribute DOM can be modified, create/remove nodes

However There is not predefined attributes link id/class

getElementById or similar methods are not applicable Since XML is not for presentation

Nods have not event handler functions Nodes have not style attribute

74

Page 75: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

XML DOM in JavaScriptDOMParser can parse an input XML string Each node have

parentNode, children, childNodes, …

Access to value of a node In the DOM, everything is a node Element nodes do not have a content value The content of an element is stored in a child node

To get content of a leaf element, the value of the first child node (text node) should got

75

Page 76: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Example: Message Parser<body>

Enter Your XML:<br />

<textarea name="inputtext" cols="50" rows="10"><root><msg><from></from><to></to><body></body></msg></root></textarea>

<input type="button" onclick="parse()" value="Parse" /> <br />

<div name="outputdiv" style="border-style:solid; border-width:1px; width:50%;"></div>

</body>

76

Page 77: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Example: Message Parserfunction parse(){

output = "";input = document.getElementsByName("inputtext")[0].value;parser = new DOMParser();xmlDoc = parser.parseFromString(input,"text/xml");messages = xmlDoc.getElementsByTagName("root")[0].children;for(i=0; i < messages.length; i++){

msg = messages[i];fromNode = msg.getElementsByTagName("from")[0];fromText = fromNode.childNodes[0].nodeValue;toNode = msg.getElementsByTagName("to")[0];toText = toNode.childNodes[0].nodeValue;bodyNode = msg.getElementsByTagName("body")[0];bodyText = bodyNode.childNodes[0].nodeValue;output = output + fromText +" sent following message to

" + toText + "<br /> ''" + bodyText +"''<hr />"}document.getElementsByName("outputdiv")[0].innerHTML = output;

}

77

Page 78: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

OutlineIntroductionNamespacesValidationPresentationXML Processing (using JavaScript)Conclusion

78

Page 79: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Conclusion: XML Technologies XHTML

A stricter and cleaner XML based version of HTML

XSL (Extensible Style Sheet Language) XSL consists of three parts: XSLT (XSL Transform) - transforms XML into other format XPath - a language for navigating XML documents

DTD (Document Type Definition) A standard for defining the legal elements

XSD (XML Schema) An XML-based alternative to DTD

79

Page 80: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Conclusion: XML Technologies SVG (Scalable Vector Graphics)

Defines graphics in XML format

XQuery (XML Query Language) An XML based language for querying XML data

XLink (XML Linking Language) A language for creating hyperlinks in XML documents

XPointer (XML Pointer Language) Allows the XLink hyperlinks to point to more specific parts in

the XML document

80

Page 81: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Conclusion XML is easy and powerful technology

To describe data structure To exchange To process & transform

XML application beyond web Image format: Scalable Vector Graphics (SVG) Everywhere to save/restore structured data

Microsoft Office, …

Other related technologies in data exchange JSON (java script), Protocol Buffer (Google), Thrift (Apache)

81

Page 82: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

Answers Q6.1) Which technology?

Text based! XML: A markup met-language with user defined tags

Q6.2) Is data correctly encoded? XML Validation: DTD and Schema

Q6.3) How to access the data in web pages? Parse XML to DOM, we know how to work with DOM

Q6.4) How to present the data? CSS for XML XPATH to select element, XSLT to translate XML to HTML

82

Page 83: XML Internet Engineering Spring 2014 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology

ReferencesReading Assignment: Chapter 7 of

“Programming the World Wide Web”David Hunter, et.al, “Beginning XML,”

chapters 1-5 & chapter 8Andrew H. Watt, “Sams Teach Yourself XML

in 10 Minutes,” chapters 1-4, chapters 8-10http://w3schools.com/xsl/default.asp

83