Unit 2 Notes
Unit 2 Notes
Unit 2 Notes
Introduction to XML
Example:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
</note>
But still, the XML above does not DO anything. XML is just information wrapped in
tags.
• HTML was designed to display data - with focus on how data looks
XML Tree
• XML documents form a tree structure that starts at "the root" and branches to "the
leaves".
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
• The terms parent, child, and sibling are used to describe the relationships between
elements.
• Parents have children. Children have parents. Siblings are children on the same
level (brothers and sisters).
• All elements can have text content (Harry Potter) and attributes
(category="cooking").
Self-Describing Syntax
<bookstore>
<book category="cooking">
</book>
• The syntax rules of XML are very simple and logical. The rules are easy to learn,
and easy to use.
• XML documents must contain one root element that is the parent of all other
elements:
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
• 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: The XML prolog does not have a closing tag! This is not an error. The prolog
is not a part of the XML document.
• 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 correct</message>
• "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
• XML elements can have attributes in name/value pairs just like in HTML.
• In XML, the attribute values must always be quoted:
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
Entity References
• To avoid this error, replace the "<" character with an entity reference:
• Only < and & are strictly illegal in XML, but it is a good habit to replace > with >
as well.
Comments in XML
• XML does not truncate multiple white-spaces (HTML truncates multiple white-
spaces to one single white-space):
• Windows applications store a new line as: carriage return and line feed (CR+LF).
• Unix and Mac OSX use LF.
• Old Mac systems use CR.
• XML stores a new line as LF.
• XML documents that conform to the syntax rules above are said to be "Well
Formed" XML documents.
XML Elements
<price>29.99</price>
<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>
<element></element>
<element />
• The two forms produce identical results in XML software (Readers, Parsers,
Browsers).
• Empty elements can have attributes.
Lower
<firstname> All letters lower case
case
Upper
<FIRSTNAME> All letters upper case
case
XML Attributes
• Attribute values must always be quoted. Either single or double quotes can be
used.
• For a person's gender, the <person> element can be written like this:
<person gender="female">
• or like this:
<person gender='female'>
• If the attribute value itself contains double quotes you can use single quotes, like
in this example:
<gangster name='George "Shotgun" Ziegler'>
---------------------------------------------------------------------------------------------------------------
XML DTD
What is a DTD?
• The DOCTYPE declaration above contains a reference to a DTD file. The content of
the DTD file is shown and explained below.
XML DTD
• The purpose of a DTD is to define the structure and the legal elements and
attributes of an XML document:
Note.dtd:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
Example
• With a DTD, independent groups of people can agree to use a standard DTD for
interchanging data.
• With a DTD, you can verify that the data you receive from the outside world is
valid.
• You can also use a DTD to verify your own data
--------------------------------------------------------------------------------------------------------------
XML Schema
• An XML Schema describes the structure of an XML document, just like a DTD.
• An XML document with correct syntax is called "Well Formed".
• An XML document validated against an XML Schema is both "Well Formed" and
"Valid".
XML Schema
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
• With XML Schema, your XML files can carry a description of its own format.
• With XML Schema, independent groups of people can agree on a standard for
interchanging data.
• With XML Schema, you can verify data.
XML Schemas Support Data Types
One of the greatest strengths of XML Schemas is the support for data types:
Another great strength about XML Schemas is that they are written in XML:
-----------------------------------------------------------------------------------------------------------------
XML Namespaces
Name Conflicts
• In XML, element names are defined by the developer. This often results in a conflict
when trying to mix XML documents from different XML applications.
• This XML carries HTML table information:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
• This XML carries information about a table (a piece of furniture):
<table>
<width>80</width>
<length>120</length>
</table>
• If these XML fragments were added together, there would be a name conflict. Both
contain a <table> element, but the elements have different content and meaning.
• A user or an XML application will not know how to handle these differences.
• Solving the Name Conflict Using a Prefix
• Name conflicts in XML can easily be avoided using a name prefix.
• This XML carries information about an HTML table, and a piece of furniture:
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
• In the example above, there will be no conflict because the two <table> elements
have different names.
• When using prefixes in XML, a namespace for the prefix must be defined.
• The namespace can be defined by an xmlns attribute in the start tag of an element.
• The namespace declaration has the following syntax. xmlns:prefix="URI".
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="https://www.w3schools.com/furniture">
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
• The xmlns attribute in the first <table> element gives the h: prefix a qualified
namespace.
• The xmlns attribute in the second <table> element gives the f: prefix a qualified
namespace.
• When a namespace is defined for an element, all child elements with the same
prefix are associated with the same namespace.
• Namespaces can also be declared in the XML root element:
<root xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="https://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
• Defining a default namespace for an element saves us from using prefixes in all the
child elements. It has the following syntax:
xmlns="namespaceURI"
<table xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
<table xmlns="https://www.w3schools.com/furniture">
<width>80</width>
<length>120</length>
</table>
• XSLT is a language that can be used to transform XML documents into other
formats.
• The XML document below, is a document used to transform XML into HTML.
• The namespace "http://www.w3.org/1999/XSL/Transform" identifies XSLT
elements inside an HTML document:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr>
<th style="text-align:left">Title</th>
<th style="text-align:left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
-----------------------------------------------------------------------------------------------------------------
XPath
What is XPath?
XPath Example
• In the table below we have listed some XPath expressions and the result of the
expressions:
---------------------------------------------------------------------------------------------------------------
XSLT
• XSLT is far more sophisticated than CSS. With XSLT you can add/remove elements
and attributes to or from the output file. You can also rearrange and sort elements,
perform tests and make decisions about which elements to hide and display, and
a lot more.
• XSLT uses XPath to find information in an XML document.
XSLT Example
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<calories>650</calories>
</food>
<food>
<price>$7.95</price>
<calories>900</calories>
</food>
<food>
<price>$8.95</price>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough
bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<calories>950</calories>
</food>
</breakfast_menu>
<html xsl:version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<body style="font-family:Arial;font-size:12pt;background-
color:#EEEEEE">
<xsl:for-each select="breakfast_menu/food">
<div style="background-color:teal;color:white;padding:4px">
<xsl:value-of select="price"/>
</div>
<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
<p>
<xsl:value-of select="description"/>
<span style="font-style:italic"> (<xsl:value-of select="calories"/>
calories per serving)</span>
</p>
</div>
</xsl:for-each>
</body>
</html>
-----------------------------------------------------------------------------------------------------------------
JSON - Introduction
JSON Example
• The JSON format is syntactically similar to the code for creating JavaScript objects.
Because of this, a JavaScript program can easily convert JSON data into JavaScript
objects.
• Since the format is text only, JSON data can easily be sent between computers, and
used by any programming language.
• JavaScript has a built in function for converting JSON strings into JavaScript
objects:
JSON.parse()
• JavaScript also has a built in function for converting an object into a JSON string:
JSON.stringify()
• You can receive pure text from a server and use it as a JavaScript object.
• You can send a JavaScript object to a server in pure text format.
• You can work with data as JavaScript objects, with no complicated parsing and
translations.
Storing Data
• When storing data, the data has to be a certain format, and regardless of where
you choose to store it, text is always one of the legal formats.
• JSON makes it possible to store JavaScript objects as text
JSON Syntax
Example
"name":"John"
JSON
{"name":"John"}
JavaScript
{name:"John"}
JSON Values
JSON
{"name":"John"}
In JavaScript, you can write string values with double or single quotes:
JavaScript
{name:'John'}
JavaScript Objects
• Because JSON syntax is derived from JavaScript object notation, very little extra
software is needed to work with JSON within JavaScript.
• With JavaScript you can create an object and assign data to it, like this:
Example
Example
// returns John
person.name;
Example
// returns John
person["name"];
Example
person.name = "Gilbert";
person["name"] = "Gilbert";
• You will learn how to convert JavaScript objects into JSON later in this tutorial.
• The same way JavaScript objects can be written as JSON, JavaScript arrays can also
be written as JSON.
JSON Files
• a string
• a number
• an object (JSON object)
• an array
• a Boolean
• null
• a function
• a date
• undefined
JSON Strings
Example
{"name":"John"}
JSON Numbers
Example
{"age":30}
JSON Objects
Example
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
JSON Arrays
Example
{
"employees":["John", "Anna", "Peter"]
}
JSON Booleans
Example
{"sale":true}
JSON null
Example
{"middlename":null}
JSON.parse()
• Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
• Make sure the text is in JSON format, or else you will get a syntax error.
• Use the JavaScript object in your page:
Example
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML = obj.name;
</script>
JSON.stringify()
• You will learn how to send JSON to a server in the next chapters.
Example
Storing Data
• When storing data, the data has to be a certain format, and regardless of where
you choose to store it, text is always one of the legal formats.
• JSON makes it possible to store JavaScript objects as text.
Example
// Storing data:
const myObj = {name: "John", age: 31, city: "New York"};
const myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
let text = localStorage.getItem("testJSON");
let obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
JSON Object
JavaScript Objects
Example
Example
• You can also access object values by using bracket ([]) notation:
Example
Looping an Object
Example
• In a for-in loop, use the bracket notation to access the property values:
Example
JSON Array
JavaScript Arrays
Example
Example
myArray[0];
Arrays in Objects
Example
{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
}
Example
myObj.cars[0];
Example
Example