Unit-3: "Other XML Technologies"
Module-3
Chapter 2
Other XML Technologies
3.1 XSLT Style Sheets
The eXtensible Stylesheet Language (XSL) is a family of recommendations for
defining the presentation and transformations of XML documents.
o It consists of three
o a)related standards: XSL Transformations (XSLT),
o b)XML Path Language (XPath),
o c)XSL Formatting Objects (XSL-FO).
XSLT style sheets are used to transform XML documents into different forms or
formats, perhaps using different DTDs.
One common use for XSLT is to transform XML documents into XHTML
documents, primarily for display.
In the transformation of an XML document, the content of elements can be moved,
modified, sorted, and converted to attribute values, among other things.
XSLT style sheets are XML documents, so they can be validated against DTDs. They
can even be transformed with the use of other XSLT style sheet.
3.3.1 Overview of XSLT
XSLT is actually a simple functional-style programming language.
Included in XSLT are functions, parameters, names to which values can be bound,
selection,constructs, and conditional expressions for multiple selection.
The syntactic structure of XSLT is XML, so each statement is specified with an
element.
XSL programs are based on the programs written in the LISP-based functional
languages COMMON LISP and Scheme.
XSLT Processor take an input as XML document and XSLT document
The XSLT document is the program to be executed.
Xml document is the input data to the program
Parts of the XML document are selected, possibly modified with parts of XSLT
document to form a new document called an XSL document.
An XSLT document consists primarily of one or more templates, which use XPath to
describe element–attribute patterns in the input XML document.
Dept of CSE,GST,Bengaluru Page 1
Unit-3: "Other XML Technologies"
So, each template describes a function that is executed whenever the XSLT processor
finds a match to the template’s pattern
If a template matches an element, the element is not processed until the closing
tag is found. When a template matches an element, the child elements of that element
may or may not be processed.
One XSLT model of processing XML data is called the template-driven model, which
works well when the data consists of multiple instances of highly regular data
collections, as with files containing records.
XSLT can also deal with irregular and recursive data, using template fragments in
what is called the data-driven model.
3.3.2 XSL Transformation for Presentation
As a simple example of an xml document that can be used to illustrate XSLT
formatting consider the following
[Link]
<?xml version="1.0" encoding ="utf-8"?>
<?xml-stylesheet type ="text/xsl" href="[Link]"?>
<plane>
<year> 1977 </year>
<make> Cessna </make>
<model> Maruthi </model>
<color> Light blue and white </color>
</plane>
An XSLT style sheet is an xml document whose root element is the special purpose
element stylesheet.
The starting part of style sheet should have
o <xsl:stylesheet version="1.0"
xmlns:xsl="[Link]
A style-sheet document must include at least one template element.
In many XSLT documents, a template is included to match the root node of the XML
document. This can be done in two ways.
One way is to use the Xpath expression “/”, as in
o <xsl:template match =“/”>
The alternative to using “/” is to use the actual root of the document.
In the example [Link], the document root is plane. Every XSLT style sheet should
include a template for the root node
<xsl:template match=“plane”>
<html><head><title>Welcome </title><body>
………….
</body></html>
</xsl:template>
• The template for the root node is implicitly applied. However, all other templates in
an XSLT document must be explicitly applied to the XML document. This can be
done in several ways.
• The apply-templates element applies appropriate templates to the descendant nodes of
the current node.
Dept of CSE,GST,Bengaluru Page 2
Unit-3: "Other XML Technologies"
• This element can include a select attribute to specify the descendant nodes whose
templates should be applied.
• Template elements are of two distinct kinds: those that literally contain content and
those that specify content to be copied from the associated XML document.
• XSLT elements that represent XHTML elements often are used to specify content.
XSLT elements have the appearance of their associated XHTML elements, like the
following XHTML element
[Link]
<?xml version="1.0" encoding ="utf-8"?>
<xsl:stylesheet version ="1.0"
xmlns:xsl="[Link]
<xsl:template match ="plane">
<html><head><title> Style sheet for [Link] </title>
</head>
<body>
<h2> Airplane discription </h2>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<xsl:template match ="year">
<span style= "font-style:italic;color:blue;">year: </span>
<xsl:value-of select ="." /> <br/>
</xsl:template>
<xsl:template match ="make">
<span style= "font-style:italic;color:blue;">make </span>
<xsl:value-of select ="." /> <br/>
</xsl:template>
<xsl:template match ="model">
<span style= "font-style:italic;color:blue;">model: </span>
<xsl:value-of select ="." /> <br/>
</xsl:template>
<xsl:template match ="color">
<span style= "font-style:italic;color:blue;">color: </span>
<xsl:value-of select ="." /> <br/>
</xsl:template>
</xsl:stylesheet>
Dept of CSE,GST,Bengaluru Page 3
Unit-3: "Other XML Technologies"
There is actually no need to include templates for all the child nodes of plane because
the value of select element finds them and apply templates can be removed
The following xsl document produces the same output as previous
[Link]
<?xml version="1.0" encoding ="utf-8"?>
<xsl:stylesheet version ="1.0"
xmlns:xsl="[Link]
<xsl:template match ="plane">
<html><head><title> Style sheet for [Link] </title>
</head>
<body>
<h2> Airplane discription </h2>
<span style= "font-style:italic;color:blue;">year: </span>
<xsl:value-of select ="year" /> <br/>
<span style= "font-style:italic;color:blue;">make </span>
<xsl:value-of select ="make" /> <br/>
<span style= "font-style:italic;color:blue;">model: </span>
<xsl:value-of select ="model" /> <br/>
<span style= "font-style:italic;color:blue;">color: </span>
<xsl:value-of select ="color" /> <br/>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Template Repeating
The XSLT template used for one plane can be used repeatedly with the for-each
element, which employs a select attribute to specify an element in the XML data.
The value of the select attribute is a pattern, which is a path expression that specifies
an element. Any child elements of the specified element are included.
Example
Dept of CSE,GST,Bengaluru Page 4
Unit-3: "Other XML Technologies"
[Link]
<?xml version="1.0" encoding ="utf-8"?>
<?xml-stylesheet type ="text/xsl" href="[Link]"?>
<planes>
<plane>
<year> 1977 </year>
<make> Cessna </make>
<model> Maruthi </model>
<color> Light blue and white </color>
</plane>
<plane>
<year> 1960 </year>
<make> Piper</make>
<model> Maruthi </model>
<color> white </color>
</plane>
</planes>
[Link]
<?xml version="1.0" encoding ="utf-8"?>
<xsl:stylesheet version ="1.0"
xmlns:xsl="[Link]
<xsl:template match ="planes">
<h2> Airplane discription </h2>
<xsl:for-each select ="plane">
<span style= "font-style:italic;color:blue;">year: </span>
<xsl:value-of select ="year" /> <br/>
<span style= "font-style:italic;color:blue;">make </span>
<xsl:value-of select ="make" /> <br/>
<span style= "font-style:italic;color:blue;">model: </span>
<xsl:value-of select ="model" /> <br/>
<span style= "font-style:italic;color:blue;">color: </span>
<xsl:value-of select ="color" /> <br/>
</xsl:for-each>
</xsl:template>
3.2 X-PATH
XPath is an official recommendation of the World Wide Web Consortium (W3C).
It defines a language to find information in an XML file.
It is used to traverse elements and attributes of an XML document.
Dept of CSE,GST,Bengaluru Page 5
Unit-3: "Other XML Technologies"
XPath provides various types of expressions which can be used to enquire relevant
information from the XML document.
Structure Definitions − XPath defines the parts of an XML document like element,
attribute, text, namespace, processing-instruction, comment, and document nodes
Path Expressions − XPath provides powerful path expressions select nodes or list of
nodes in XML documents.
Standard Functions − XPath provides a rich library of standard functions for
manipulation of string values, numeric values, date and time comparison, node and
QName manipulation, sequence manipulation, Boolean values etc.
Major part of XSLT − XPath is one of the major elements in XSLT standard and is
must have knowledge in order to work with XSLT documents.
a)Selecting Nodes
XPath uses path expressions to select nodes in an XML document.
The node is selected by following a path or steps.
The most useful path expressions are listed below
Path Expression Examples
i)Absolute Path
Location path specifies the location of node in XML document.
Dept of CSE,GST,Bengaluru Page 6
Unit-3: "Other XML Technologies"
If location path starts with root node or with '/' then it is an absolute path.
Eg:
<xsl:for-each select = "/class/student">
select student nodes within class root node.
<p><xsl:value-of select = "/class/student/firstname"/></p>
select firstname of a student node within class root node.
ii)Relative Path
If location path starts with the node that has been selected then it is a relative path.
Eg:
firstname − select firstname related to student nodes.
<p><xsl:value-of select = "firstname"/></p>
b)Standard Functions
a) Comparision Operators- Comparision operators to compare values.
Eg:(< ,>,=,<=,>=,==)
b) Boolean Operators- Boolean operators to check ‘and’, ‘or’ & ‘not’
functionalities.
Eg:(and ,or, not )
c) Number Functions/Operators- Operators/Functions on numbers.
Eg: (+,-,*,div,mod)
d) String Functions- Various string functions.
Eg:starts-with(string1, string2), concat(string1, string2, ...),
e) Node Functions/Operators -Various functions and operators acting on nodes.
Eg:(/,//,..,|)
c)Wild Cards
XPath defines the following wildcards on nodes to be used with the XPath expressions.
a)*-used to match any node.
b).-used to match the current node in context.
c)@*-used to match any attribute
d)node()-used to match node of any type
d)Predicates
Predicate refers to the XPath expression written in square brackets.
a. It refers to restrict the selected nodes in a node set for some condition.
b. class/student[1]-Select first student element which is child of the class element.
c. class/student[last()]-Select last student element which is child of the class element.
d. class/student[@rolllno = 493]-Select student element with rollno 493.
e. /class/student[marks>85]-Select student element with marks > 85.
Example:[Link]
?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "[Link]"?>
<class>
<student rollno = "393">
Dept of CSE,GST,Bengaluru Page 7
Unit-3: "Other XML Technologies"
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
[Link]
<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "1.0"
xmlns:xsl = "[Link]
<xsl:template match = "/">
<html>
<body>
<h2>Students</h2>
<table border = "1">
<tr bgcolor = "blue">
<th>Roll No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Marks</th>
</tr>
<xsl:for-each select = "class/student">
<tr>
<td> <xsl:value-of select = "@rollno"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "marks"/></td>
</tr>
</xsl:for-each>
Dept of CSE,GST,Bengaluru Page 8
Unit-3: "Other XML Technologies"
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
3.3 XQuery
XQuery is the language for querying XML data
XQuery for XML is like SQL for databases
XQuery is built on XPath expressions
XQuery is supported by all major databases
Transform XML data to XHTML
Search Web documents for relevant information
Eg:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>38.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>
Select Nodes From "[Link]"?
• XQuery uses functions to extract data from XML documents.
• The doc() function is used to open the "[Link]" file:
doc("[Link]")
Path Expression
XQuery uses path expressions to navigate through elements in an XML document.
• The following path expression is used to select all the title elements in the
"[Link]" file:
doc("[Link]")/bookstore/book/title
Predicates
• XQuery uses predicates to limit the extracted data from XML documents.
• The following predicate is used to select all the book elements under the bookstore
element that have a price element with a value that is less than 30:
doc("[Link]")/bookstore/book[price<30]
Dept of CSE,GST,Bengaluru Page 9
Unit-3: "Other XML Technologies"
3.4 XQuery FLWOR Expressions
FLWOR (pronounced "flower") is an acronym for "For, Let, Where, Order by,
Return".
For - selects a sequence of nodes
Let - binds a sequence to a variable
Where - filters the nodes
Order by - sorts the nodes
Return - what to return (gets evaluated once for every node)
Examples
a)doc("[Link]")/bookstore/book[price>30]/title
for $x in doc("[Link]")/bookstore/book
where $x/price>30
return $x/title
Result:
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>
b)With FLWOR you can sort the result:
for $x in doc("[Link]")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
Result:
<title lang="en">Learning XML</title>
<title lang="en">XQuery Kick Start</title>
The for clause selects all book elements under the bookstore element into a variable
called $x.
The where clause selects only book elements with a price element with a value
greater than 30.
The order by clause defines the sort-order. Will be sort by the title element.
The return clause specifies what should be returned. Here it returns the title elements.
3.5 JSON
Definition:
JSON (JavaScript Object Notation) is a lightweight text-data interchange format used
to store information in an organized manner for transmitting data between server and web
application.
JSON is a lightweight text-data interchange format.
JSON is not a programming language.
XML is an alternative to JSON. However, JSON objects have several advantages
instead of XML.
JSON media type is application/json and file extension is .json.
Dept of CSE,GST,Bengaluru Page 10
Unit-3: "Other XML Technologies"
JSON has extended from JavaScript scripting language.
JSON uses JavaScript syntax to describe data objects, but still, the JSON language is
platform-independent.
Features of JSON
JSON is Scalable. Because of language-independent, it works with most of the
modern programming language.
JSON is lightweight.
JSON is easy to read and write.
JSON is a text-based, human-readable data exchange format.
JSON Syntax Rules:
Data is represented as name/value pairs and isolated by the comma.
Curly braces organize objects, and the colon isolates each name.
Square brackets hold the array, and commas separate values.
Let us take simple way to create JSON data representation. A name/value pair is the name of a
field, followed by a colon and value.
Ex: “username” : “thirumalai”
The JSON values are different data types, they are
String Use in double quotes
Number Must be integer or floating point
Object An unordered collection of key: value pairs, used in curly brackets
Array An ordered sequence of values, used in square brackets
Boolean Must be true or false
null For empty value
JSON values cannot be one of the following data types:
• a function
• a date
• undefined
1)Number:
It is a double precision floating-point format in JavaScript and it depends on implementation.
Octal and hexadecimal formats are not used.
No NaN or Infinity is used in Number.
Syntax
var json-object-name = {"string" : number_value, .......}
Dept of CSE,GST,Bengaluru Page 11
Unit-3: "Other XML Technologies"
Example
var obj = {"marks": 97}
2)String:
It is a sequence of zero or more double quoted Unicode characters with backslash escaping.
Character is a single character string i.e. a string with length 1.
Syntax
var json-object-name = { string : "string value", .......}
Example
var obj = {"name": "Amit"}
3)Boolean
This data type can be either true or false.
Syntax
var json-object-name = { string : true}
Example
var obj = { "result" : true }
4)Nullable
It is just a define nullable value.
Syntax
var json-object-name = { string : null }
Example:
"result" : true,
"grade" : null,
"rollno" : 210
Dept of CSE,GST,Bengaluru Page 12
Unit-3: "Other XML Technologies"
5)JSON Objects
JSON objects are formed using the curly braces which surrounds its data. These are written in
a key-value pairing format.
It is to be noted that the keys must have to be a string, and the value in the key-value pair
must have to be anyone among the data types of JSON.
Moreover, the key and value are separated by a colon (:) and where there are multiple key-
value pairs, all of these are separated by a comma (,)
Example:
Objects can contain multiple keys: value pairs:
"userName": "Alex",
"userAge": 26
It's also easy to understand and equals to the Javascript statement:
userName = "Alex"
userAge = 26
Creating Objects
[Link] Object: You can also create empty JSON objects.
The syntax will be:
var obj1 = {};
[Link] Object: you can also create new objects using this syntax:
var obj2 = new Object();
[Link] object with Attribute: Another way of creating objects is by assigning multiple
attributes where the key will be the string, and the value can be either string or a numeric
value. Let us take an example where a JSON file will store professor's data and their salaries.
var prof_details={
"name ": "Pavithra“, "salary": 50000};
Dept of CSE,GST,Bengaluru Page 13
Unit-3: "Other XML Technologies"
Accessing and Deleting
Access an object
Sal=prof_details[salary];
Or else
Foreach $x in prof_details
$x[sal];
Delete an object
Delete prof_details.sal;
Nested Object Elements
It is also possible to write a JSON object within another object. This will look something like
this:
var prof={
"name": "Ambrush",
"age": 24,
"subjects": {
"s1": "C++",
"s2": "software engineering",
"s3": "Data Science"
}}
6)Json Arrays
it is an ordered collection of values
These are enclosed in square brackets which means that array begins with .[. and ends
with .]..
The values are separated by , (comma).
Array indexing can be started at 0 or 1.
Arrays should be used when the key names are sequential integers.
Syntax
[ value, .......]
Example
{
Dept of CSE,GST,Bengaluru Page 14
Unit-3: "Other XML Technologies"
"books": [
{ "language":"Java" , "edition":"second" },
{ "language":"C++" , "lastName":"fifth" },
{ "language":"C" , "lastName":"third" }
]
}
JSON AND JAVASCRIPT
Example
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Array from JSON</h2>
<p id="demo"></p>
<script>
const myJSON = '["Ford", "BMW", "Fiat"]';
const myArray = [Link](myJSON);
[Link]("demo").innerHTML = myArray;
</script>
</body>
</html>
• eval() function can be used to execute any JavaScript; this represents a potential
security problem.
• JSON parser is used to convert a JSON text to a JavaScript object, JSON parser only
recognize JSON text, and the script does not compile.
• JSON Parser Example:
obj = [Link](data);
Differences in XML vs JSON
XML (Extensible Markup JSON (JavaScript Object Notation).
Language).
Slower in constructing an XML Faster than XML for constructing data representation
data representation format. format.
Less simple to read than JSON. JSON is simpler to read than XML.
Dept of CSE,GST,Bengaluru Page 15
Unit-3: "Other XML Technologies"
XML is a type of markup JSON is a means to characterize objects.
language.
XML is a bit more flexible in JSON is not much flexible as compared to XML, but
detailing of data. since it deals with objects, so it does not need much
detail.
XML does not support the JSON supports representing data in the form of an array.
concept of array
XML is more secure as JSON seems less secured as compared to XML.
compared to JSON.
In parsing, the XML DOM In the case of parsing, the eval method of JavaScript can
(Document Object Model) parse JSON data.
allows access and editing of
XML data.
XML data representing format JSON data format is self-describing.
is not self-describing.
.json
{
"result": [
{
"name": "John",
"marks": {
"math": "78",
"english": "90",
"chemistry": "64",
"physics": "89"
}
},
.....
]
}
.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript - Display JSON data as list</title>
</head>
<body>
<h1>Display JSON Data as list.</h1>
<button onclick="showList()">Show List</button>
Dept of CSE,GST,Bengaluru Page 16
Unit-3: "Other XML Technologies"
<script>
function showList(){
fetch("./lib/examples/[Link]")
.then(response => [Link]())
.then(data => createList(data));
}
function createList(data) {
const mainUL = [Link]('ol');
for (let i = 0; i < [Link]; i++) {
const studentLI = [Link]('li');
[Link] = [Link][i].name;
// create list for marks
const marksUL = [Link]('ul');
for (var key in [Link][i].marks) {
const marksLI = [Link]('li');
[Link] = key + ': ' + [Link][i].marks[key];
[Link](marksLI);
}
// append marks list to studentLI
[Link](marksUL);
// append student list to mainUL
[Link](studentLI);
}
// append mainUL to body
[Link](mainUL);
}
</script>
</body>
</html>
Dept of CSE,GST,Bengaluru Page 17
Unit-3: "Other XML Technologies"
Output
Dept of CSE,GST,Bengaluru Page 18