Unit Iii
Unit Iii
Introduction to XML – XML Syntax – DTD – Schemas – XML DOM – XPath – XSLT –
Introduction to AJAX – XML HTTP – Request & Response – AJAX XML – Implementing
Web APIs – Third Party APIs
Introduction to XML:
Extensible Markup Language (XML) is a markup language that defines a set of rules for
encoding documents in a format that is both human-readable and machine-readable. The design
goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual
data format with strong support via Unicode for different human languages. Although the
design of XML focuses on documents, the language is widely used for the representation of
arbitrary data structures such as those used in web services.
EXAMPLE :
XML code for a note is given below
HTML code for the note is given below
<!DOCTYPE html>
<html>
<h1>Note</h1>
<body>
<p>To:RAJ
<br>
From:RAVI
</p>
<h1>Reminder</h1>
<p>Meeting at 8am</p>
</body>
</html>
OUTPUT:
XML Syntax:
XML (Extensible Markup Language) syntax is used to structure and store data in a hierarchical
format. Here are the key syntax rules:
The XML document can start with a declaration specifying the version and encoding:
2. Root Element
Every XML document must have a single root element that contains all other elements.
<books>
<book>
<title>Cryptography Handbook</title>
<author>John Doe</author>
</book>
</books>
4. Case Sensitivity
XML is case-sensitive.
5. Attributes
Elements can have attributes, but attribute values must be enclosed in quotes.
<title>Network Security</title>
</book>
Element names:
• Should not use reserved XML characters like <, >, or &.
8. Comments
Comments are similar to HTML but cannot be nested.
A Document Type Definition (DTD) defines the structure, elements, and attributes of an XML
document to enforce consistency and validity.
2. External DTD – Defined in a separate file and referenced in the XML document.
Internal DTD
<!DOCTYPE books [
]>
<books>
<book>
<title>Cryptography Handbook</title>
<author>John Doe</author>
</book>
</books>
Explanation
• <!ELEMENT books (book+)> → books contains one or more book elements.
• <!ELEMENT book (title, author)> → Each book contains title and author.
External DTD
<books>
<book>
<title>Cryptography Handbook</title>
<author>John Doe</author>
</book>
</books>
Elements Declaration
• (A | B | C) → Either A, B, or C (choice).
Attributes Declaration
Example:
An XML Schema (XSD) defines the structure, data types, and constraints for an XML
document, ensuring valid and consistent data.
• Uses XML syntax (unlike DTD, which has its own syntax).
Here’s a simple example of an XML Schema (XSD) and an XML file that conforms to it.
<book id="101">
<title>Cryptography Handbook</title>
<author>John Doe</author>
<price>49.99</price>
</book>
</books>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="books">
<xs:complexType>
<xs:sequence>
<xs:complexType>
<xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Explanation
<xs:element name="price">
<xs:simpleType>
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0.99"/>
<xs:maxInclusive value="999.99"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Data Types Not Supported Strongly Typed (string, int, date, etc.)
The XML Document Object Model (DOM) class is an in-memory representation of an XML
document. The DOM allows you to programmatically read, manipulate, and modify an XML
document. The XmlReader class also reads XML; however, it provides non-cached, forward-
only, read-only access. This means that there are no capabilities to edit the values of an attribute
or content of an element, or the ability to insert and remove nodes with the XmlReader. Editing
is the primary function of the DOM. It is the common and structured way that XML data is
represented in memory, although the actual XML data is stored in a linear fashion when in a
file or coming in from another object. The following is XML data.
Input
XMLCopy
<?xml version="1.0"?>
<books>
<book>
<author>Carson</author>
<price format="dollar">31.95</price>
<pubdate>05/01/2001</pubdate>
</book>
<pubinfo>
<publisher>MSPress</publisher>
<state>WA</state>
</pubinfo>
</books>
The following illustration shows how memory is structured when this XML data is read into
the DOM structure.
X
ML document structure
Within the XML document structure, each circle in this illustration represents a node, which is
called an XmlNode object. The XmlNode object is the basic object in the DOM tree.
The XmlDocument class, which extends XmlNode, supports methods for performing
operations on the document as a whole (for example, loading it into memory or saving the
XML to a file. In addition, XmlDocument provides a means to view and manipulate the nodes
in the entire XML document. Both XmlNode and XmlDocument have performance and
usability enhancements and have methods and properties to:
• Access and modify nodes specific to the DOM, such as element nodes, entity reference
nodes, and so on.
• Retrieve entire nodes, in addition to the information the node contains, such as the text
in an element node.
Note
If an application does not require the structure or editing capabilities provided by the DOM,
the XmlReader and XmlWriter classes provide non-cached, forward-only stream access to
XML. For more information, see XmlReader and XmlWriter.
Node objects have a set of methods and properties, as well as basic and well-defined
characteristics. Some of these characteristics are:
• Nodes have a single parent node, a parent node being a node directly above them. The
only nodes that do not have a parent is the Document root, as it is the top-level node
and contains the document itself and document fragments.
• Most nodes can have multiple child nodes, which are nodes directly below them. The
following is a list of node types that can have child nodes.
o Document
o DocumentFragment
o EntityReference
o Element
o Attribute
One characteristic of the DOM is how it handles attributes. Attributes are not nodes that are
part of the parent, child, and sibling relationships. Attributes are considered a property of the
element node and are made up of a name and a value pair. For example, if you have XML data
consisting of format="dollar" associated with the element price, the word format is the name,
and the value of the format attribute is dollar. To retrieve the format="dollar" attribute of
the price node, you call the GetAttribute method when the cursor is located at the price element
node. For more information, see Accessing Attributes in the DOM.
As XML is read into memory, nodes are created. However, not all nodes are the same type. An
element in XML has different rules and syntax than a processing instruction. Therefore, as
various data is read, a node type is assigned to each node. This node type determines the
characteristics and functionality of the node.
Microsoft has extended the APIs that are available in the World Wide Web Consortium (W3C)
DOM Level 1 and Level 2 to make it easier to work with an XML document. While fully
supporting the W3C standards, the additional classes, methods, and properties add functionality
beyond what can be done using the W3C XML DOM. New classes enable you to access
relational data, giving you methods for synchronizing with ADO.NET data, simultaneously
exposing data as XML. For more information, see Synchronizing a DataSet with an
XmlDataDocument.
The DOM is most useful for reading XML data into memory to change its structure, to add or
remove nodes, or to modify the data held by a node as in the text contained by an element.
However, other classes are available that are faster than the DOM in other scenarios. For fast,
non-cached, forward-only stream access to XML, use the XmlReader and XmlWriter. If you
need random access with a cursor model and XPath, use the XPathNavigator class.
XPath
XPath can be used to navigate through elements and attributes in an XML document.
• XPath uses "path like" syntax to identify and navigate nodes in an XML do
These path expressions look very much like the path expressions you use with traditional
computer file systems:
XPath Standard Functions
boolean
ceiling
The ceiling function evaluates a decimal number and returns the smallest integer greater than
or equal to the decimal number.
choose
The choose function returns one of the specified objects based on a boolean parameter.
concat
The concat function concatenates two or more strings and returns the resulting string.
contains
The contains function determines whether the first argument string contains the second
argument string and returns boolean true or false.
count
The count function counts the number of nodes in a node-set and returns an integer.
current
The current function can be used to get the context node in an XSLT instruction.
document
The document finds a node-set in an external document, or multiple external documents, and
returns the resulting node-set.
element-available
The element-available function determines if an element is available and returns true or false.
false
The false function returns boolean false.
floor
The floor function evaluates a decimal number and returns the largest integer less than or equal
to the decimal number.
format-number
The format-number function evaluates a number and returns a string representing the number
in a given format.
function-available
The function-available function determines if a given function is available and returns boolean
true or false.
generate-id
The generate-id function generates a unique id for the first node in a given node-set and returns
a string containing that id.
id
The id function finds nodes matching the given ids and returns a node-set containing the
identified nodes.
key
The key function returns a node-set of nodes that have the given value for the given key.
lang
The lang function determines whether the context node matches the given language and returns
boolean true or false.
last
The last function returns a number equal to the context size from the expression evaluation
context.
local-name
The local-name function returns a string representing the local name of the first node in a given
node-set.
name
The name function returns a string representing the QName of the first node in a given node-
set.
namespace-uri
The namespace-uri function returns a string representing the namespace URI of the first node
in a given node-set.
normalize-space
The normalize-space function strips leading and trailing white-space from a string, replaces
sequences of whitespace characters by a single space, and returns the resulting string.
not
The not function evaluates a boolean expression and returns the opposite value.
number
The number function converts an object to a number and returns the number.
position
The position function returns a number equal to the context position from the expression
evaluation context.
round
The round function returns a number that is the nearest integer to the given number.
starts-with
The starts-with checks whether the first string starts with the second string and returns true or
false.
string
string-length
The string-length function returns a number equal to the number of characters in a given string.
substring
The substring function returns a part of a given string.
substring-after
The substring-after function returns a string that is the rest of a given string after a given
substring.
substring-before
The substring-before function returns a string that is the part of a given string before a given
substring.
sum
The sum function returns a number that is the sum of the numeric values of each node in a
given node-set.
system-property
translate
The translate function evaluates a string and a set of characters to translate and returns the
translated string.
true
unparsed-entity-url
The unparsed-entity-url() function returns the URI of the unparsed entity with the given name.
This is non-XML data referenced in the DTD of the source document.
XSLT
Uses of XSLT
• XSLT can be used for organizing large trees of XML elements. So anyone can read it.
• Since XSLT is doing the transformation on the client side. The server has to do the less
work.
• Then in order to make it as an XSLT document. We need to use the root tag called
stylesheet.
• This is the first root tag that you define within this XSLT document and it has to be
given the version. In order to access all the properties, attributes, and features you have
to include this namespace. We include a namespace xmlns and as a parameter we
pass xsl with the value “https://www.w3.org/1999/XSL/Transform”
[action]
<xsl : template>
Now XSLT document can contain one or more templates. Templates actually define the rules
that you want to place for the elements. The template has an attribute called match. In the
attribute, we try to give the Xpath expression [ match = “/” ] which tries to match the pattern
in the source XML document.
<xsl : stylesheet>
[action]
<xsl : template>
[action]
<xsl : template>
--------------------
</xsl : stylesheet>
• We create one file called movie.xml. We declare the version of XML as discussed
above. After that we include the stylesheet called movie.xsl
• We define our movies names followed by it’s attribute moviename, genre and year. We
pass movieId as the Xpath expression in the movie tag. All the movies details is
enclosed within <list></list> tag.
<list>
<genre>Fictional</genre>
<year>2001</year>
</list>
• XML
• XML
<list>
<genre>Fictional</genre>
<year>2001</year>
</movie>
<genre>Fictional</genre>
<year>2002</year>
</movie>
<genre>Fictional</genre>
<year>2004</year>
</movie>
<genre>Fictional</genre>
<year>2005</year>
</movie>
<movie movieId = "05">
<genre>Fictional</genre>
<year>2007</year>
</movie>
<genre>Fictional</genre>
<year>2009</year>
</movie>
<genre>Fictional</genre>
<year>2010</year>
</movie>
<genre>Fictional</genre>
<year>2011</year>
</movie>
</list>
• We need to include movie.xsl as a stylesheet, just like we have CSS for HTML.
• Include template with the Xpath attribute match. Since we are using only one XML file.
That’s why we use match = “/”.
• Define the structure of web page using HTML. We are displaying the data in table
format.
• We use for-each to traverse on the list. We are displaying MovieId, Moviename, genre
and year.
List of Movies
AJAX (Asynchronous JavaScript and XML) is a web development technique used to create
dynamic and interactive web applications. It allows web pages to update data asynchronously
without reloading the entire page.
2. Partial Page Updates – Only specific parts of a web page are updated instead of
reloading the entire page.
3. Improved User Experience – Faster interactions and seamless updates enhance user
experience.
3. The server processes the request and sends back the response in JSON/XML format.
4. JavaScript updates the web page dynamically based on the server response.
function loadData() {
xhr.onreadystatechange = function () {
document.getElementById("content").innerHTML = xhr.responseText;
};
xhr.send();
Explanation:
• When the request is complete (readyState == 4 and status == 200), the response is
displayed on the webpage.
AJAX Using Fetch API (Modern Approach)
function loadData() {
fetch("data.txt")
Applications of AJAX
• Loading Data from Server Without Refresh (e.g., News Feeds, Weather Updates)
XML HTTP
XMLHttpRequest (XHR) is an API in JavaScript used to interact with servers and exchange
data without needing to reload a webpage. It allows sending HTTP requests (GET, POST, etc.)
to a server and handling responses asynchronously.
Basic Syntax
};
xhr.send();
XHR Methods
XHR Properties
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
console.log(xhr.responseText);
}
};
xhr.send(data);
AJAX (Asynchronous JavaScript and XML) is a technique used to send and receive data from
a server without reloading the webpage. While JSON is more common today, XML can still
be used to exchange data.
xhr.onreadystatechange = function () {
console.log(items[i].getElementsByTagName("name")[0].textContent);
}
};
xhr.send();
<items>
<item>
<name>Product 1</name>
<price>100</price>
</item>
<item>
<name>Product 2</name>
<price>150</price>
</item>
</items>
xhr.setRequestHeader("Content-Type", "application/xml");
xhr.onreadystatechange = function () {
console.log("Response:", xhr.responseText);
};
xhr.send(xmlData);
fetch("https://example.com/data.xml")
.then(xml => {
console.log(items[i].getElementsByTagName("name")[0].textContent);
})
Web APIs allow communication between different applications over the internet. You can
either create your own API or consume third-party APIs (e.g., Google Maps, OpenWeather,
Stripe).
Since you're working with Django, here’s how you can build a simple REST API using Django
without Django REST Framework (DRF).
cd myapi
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.FloatField()
import json
def get_products(request):
products = list(Product.objects.values()) # Convert queryset to list
def add_product(request):
if request.method == "POST":
data = json.loads(request.body)
urlpatterns = [
path('products/', get_products),
path('add-product/', add_product),
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
You can fetch data from an external API inside Django using requests.
import requests
def fetch_weather(request):
api_key = "YOUR_API_KEY"
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(url)
data = response.json()
return JsonResponse(data)
• You can replace it with any other API like Google Maps, News API, etc.
4. Consuming Third-Party APIs in Angular
Since you’re working with Angular, here’s how you can fetch API data.
ng add @angular/common/http
@NgModule({
imports: [ HttpClientModule ],
})
@Component({
selector: 'app-weather',
})
weather: any;
this.http.get('https://api.openweathermap.org/data/2.5/weather?q=NewYork&appid=YOUR_
API_KEY')