0% found this document useful (0 votes)
25 views33 pages

Unit Iii

This document provides an overview of XML, including its syntax, DTD, XML Schemas, and the XML DOM. It explains the differences between XML and HTML, how to define document structures using DTD and XSD, and the functionalities of XPath for navigating XML documents. Additionally, it covers the advantages of XML Schema over DTD and the role of DOM in manipulating XML data.

Uploaded by

Sharath Jyrt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views33 pages

Unit Iii

This document provides an overview of XML, including its syntax, DTD, XML Schemas, and the XML DOM. It explains the differences between XML and HTML, how to define document structures using DTD and XSD, and the functionalities of XPath for navigating XML documents. Additionally, it covers the advantages of XML Schema over DTD and the role of DOM in manipulating XML data.

Uploaded by

Sharath Jyrt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT 3 DATA EXCHANGE AND INTERACTIVITY 9 Hrs.

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.

• XML stands for extensible Markup Language


• XML is a markup language like HTML
• XML is designed to store and transport data
• XML is designed to be self-descriptive
• Differences between XML and HTML

XML and HTML were designed with different goals:

• XML is designed to carry data emphasizing on what type of data it is.


• HTML is designed to display data emphasizing on how data looks
• XML tags are not predefined like HTML tags.
• HTML is a markup language whereas XML provides a framework for defining markup
languages.
• HTML is about displaying data,hence it is static whereas XML is about carrying
information,which makes it dynamic.

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:

1. XML Declaration (Optional)

The XML document can start with a declaration specifying the version and encoding:

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

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>

3. Properly Nested and Closed Tags

Each XML element must have a closing tag.

<message>Hello, World!</message> <!-- Correct -->

<message>Hello, World! <!-- Incorrect: No closing tag -->

4. Case Sensitivity

XML is case-sensitive.

<Author>John</Author> <!-- Different from <author>John</author> -->

5. Attributes

Elements can have attributes, but attribute values must be enclosed in quotes.

<book id="101" category="Technology">

<title>Network Security</title>

</book>

6. No Special Characters in Element Names

Element names:

• Cannot start with a number or special character.

• Cannot contain spaces.

• Should not use reserved XML characters like <, >, or &.

7. CDATA Sections (For Special Characters)

CDATA sections allow storing special characters without parsing issues.

<![CDATA[This is <not> parsed as XML.]]>

8. Comments
Comments are similar to HTML but cannot be nested.

<!-- This is a comment -->

DTD (Document Type Definition) in XML

A Document Type Definition (DTD) defines the structure, elements, and attributes of an XML
document to enforce consistency and validity.

DTD can be defined in two ways:

1. Internal DTD – Defined within the XML document.

2. External DTD – Defined in a separate file and referenced in the XML document.

Internal DTD

Defined inside the XML document using the <!DOCTYPE> declaration.

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

<!DOCTYPE books [

<!ELEMENT books (book+)>

<!ELEMENT book (title, author)>

<!ELEMENT title (#PCDATA)>

<!ELEMENT author (#PCDATA)>

]>

<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.

• <!ELEMENT title (#PCDATA)> → #PCDATA (Parsed Character Data) means it


contains text.

External DTD

Defined in a separate .dtd file and linked in the XML document.

Step 1: Create books.dtd

<!ELEMENT books (book+)>

<!ELEMENT book (title, author)>

<!ELEMENT title (#PCDATA)>

<!ELEMENT author (#PCDATA)>

Step 2: Reference DTD in XML

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

<!DOCTYPE books SYSTEM "books.dtd">

<books>

<book>

<title>Cryptography Handbook</title>

<author>John Doe</author>

</book>

</books>

DTD Rules and Syntax

Elements Declaration

<!ELEMENT element_name (child_elements)>


• (A, B, C) → Order matters (A followed by B, then C).

• (A | B | C) → Either A, B, or C (choice).

• (A*) → Zero or more occurrences of A.

• (A+) → One or more occurrences of A.

• (A?) → Zero or one occurrence of A.

Attributes Declaration

<!ATTLIST element_name attribute_name attribute_type default_value>

Example:

<!ATTLIST book id ID #REQUIRED>

Here, id is an ID and must be unique.

XML Schemas (XSD - XML Schema Definition)

An XML Schema (XSD) defines the structure, data types, and constraints for an XML
document, ensuring valid and consistent data.

Advantages of XML Schema over DTD

• Supports data types (e.g., integer, date, boolean).

• Uses XML syntax (unlike DTD, which has its own syntax).

• Allows namespace support.

• Provides stronger validation mechanisms.

Basic XML Schema (XSD) Example

Here’s a simple example of an XML Schema (XSD) and an XML file that conforms to it.

Step 1: XML Document (books.xml)

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


<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="books.xsd">

<book id="101">

<title>Cryptography Handbook</title>

<author>John Doe</author>

<price>49.99</price>

</book>

</books>

• xmlns:xsi → Declares XML Schema namespace.

• xsi:noNamespaceSchemaLocation="books.xsd" → Links the XML document to


books.xsd.

Step 2: XML Schema Definition (books.xsd)

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

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<!-- Root Element -->

<xs:element name="books">

<xs:complexType>

<xs:sequence>

<xs:element name="book" maxOccurs="unbounded">

<xs:complexType>

<xs:sequence>

<xs:element name="title" type="xs:string"/>

<xs:element name="author" type="xs:string"/>


<xs:element name="price" type="xs:decimal"/>

</xs:sequence>

<xs:attribute name="id" type="xs:integer" use="required"/>

</xs:complexType>

</xs:element>

</xs:sequence>

</xs:complexType>

</xs:element>

</xs:schema>

Explanation

• <xs:element name="books"> → Root element books.

• <xs:element name="book" maxOccurs="unbounded"> → Multiple book elements


allowed.

• <xs:complexType> → Allows nested elements inside book.

• <xs:attribute name="id" type="xs:integer" use="required"/> → Defines id as a required


integer attribute.

XSD Data Types

Type Description Example

xs:string Text values "Hello"

xs:integer Whole numbers 100

xs:decimal Floating point numbers 99.99

xs:boolean true or false true


Type Description Example

xs:date Date format (YYYY-MM-DD) 2024-03-26

XSD Restrictions (Constraints)

We can impose restrictions on elements and attributes.

<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>

• minInclusive → Minimum allowed value.

• maxInclusive → Maximum allowed value.

Difference Between DTD and XSD

Feature DTD XSD

Syntax Not XML XML-based

Data Types Not Supported Strongly Typed (string, int, date, etc.)

Namespace Support No Yes

Extensibility Limited Highly Extensible

Validation Power Weaker Stronger


XML DOM

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

The XmlDeclaration, Notation, Entity, CDATASection, Text, Comment, ProcessingInstructio


n, and DocumentType nodes do not have child nodes.

• Nodes that are at the same level, represented in the diagram by


the book and pubinfo nodes, are siblings.

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 is a major element in the XSLT standard.

XPath can be used to navigate through elements and attributes in an XML document.

• XPath stands for XML Path Language

• XPath uses "path like" syntax to identify and navigate nodes in an XML do

• XPath contains over 200 built-in functions

• XPath is a major element in the XSLT standard

• XPath is a W3C recommendation

XPath Path Expressions

XPath uses path expressions to select nodes or node-sets in an XML document.

These path expressions look very much like the path expressions you use with traditional
computer file systems:
XPath Standard Functions

XPath includes over 200 built-in functions.

boolean

The boolean function evaluates an expression and returns true or false.

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

The string function converts the given argument to a 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

The system-property function returns an object representing the given system-property.

translate

The translate function evaluates a string and a set of characters to translate and returns the
translated string.

true

The true function returns a boolean value of 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

XSLT stands for Extensible Stylesheet Language Transformation. It is an integrated concept


with an XML. It is not used for Visual effects. However, it is used for extracting or transforming
data from XML and using the combination of HTML and CSS to format them. It also has
dynamic properties, where you can do iteration and conditional statements upon a static XML
file.

Uses of XSLT
• XSLT can be used for organizing large trees of XML elements. So anyone can read it.

• It is used to transform XML – to – HTML

• Since XSLT is doing the transformation on the client side. The server has to do the less
work.

XSLT Transform Syntax Declaration

• Since it is an XML file it starts with an XML declaration.

<? xml version = "1.0" ?>

• Then in order to make it as an XSLT document. We need to use the root tag called
stylesheet.

<xsl : stylesheet version = "1.0" xmlns : xsl = "https://www.w3.org/1999/XSL/Transform">

• 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”

<xsl : template match="/" >

[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.

Document structure of XSLT

<? xml version = "1.0" ?>

<xsl : stylesheet version = "1.0" xmlns : xsl = "https://www.w3.org/1999/XSL/Transform">

<xsl : stylesheet>

<xsl : tempate match="/" >

[action]
<xsl : template>

<xsl : tempate match="/" >

[action]

<xsl : template>

--------------------

</xsl : stylesheet>

Program that displays movie names using XSLT

• 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

<?xml version = "1.0"?>

<?xml-stylesheet type = "text/xsl" href = "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>

<movie movieId = "01">

<moviename>Harry Potter and the Philosopher's Stone</moviename>

<genre>Fictional</genre>

<year>2001</year>

</list>

Example: Here is the full implementation.

• XML

• XML

<!-- file name- movie.xml-->


<?xml version = "1.0"?>

<?xml-stylesheet type = "text/xsl" href = "movie.xsl"?>

<list>

<movie movieId = "01">

<moviename>Harry Potter and the Philosopher's Stone</moviename>

<genre>Fictional</genre>

<year>2001</year>

</movie>

<movie movieId = "02">

<moviename>Harry Potter and the Chamber of Secrets</moviename>

<genre>Fictional</genre>

<year>2002</year>

</movie>

<movie movieId = "03">

<moviename>Harry Potter and the Prisoner of Azkaban </moviename>

<genre>Fictional</genre>

<year>2004</year>

</movie>

<movie movieId = "04">

<moviename>Harry Potter and the Goblet of Fire</moviename>

<genre>Fictional</genre>

<year>2005</year>

</movie>
<movie movieId = "05">

<moviename>Harry Potter and the Order of the Phoenix</moviename>

<genre>Fictional</genre>

<year>2007</year>

</movie>

<movie movieId = "06">

<moviename>Harry Potter and the Half-Blood Prince</moviename>

<genre>Fictional</genre>

<year>2009</year>

</movie>

<movie movieId = "07">

<moviename>Harry Potter and the Deathly Hallows – Part 1</moviename>

<genre>Fictional</genre>

<year>2010</year>

</movie>

<movie movieId = "08">

<moviename>Harry Potter and the Deathly Hallows – Part 2</moviename>

<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.

Output: Now try to open movie.xml file in Internet Explorer.

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.

Key Features of AJAX

1. Asynchronous Communication – AJAX allows data to be fetched or sent to a server in


the background without affecting the user interface.

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.

4. Uses Standard Web Technologies:

o JavaScript – To handle AJAX requests.


o XMLHttpRequest (XHR) or Fetch API – For server communication.

o HTML & CSS – For structuring and styling the page.

o JSON/XML – For data exchange between the client and server.

How AJAX Works?

1. A user interacts with a web page (e.g., clicking a button).

2. JavaScript sends a request to the server using XMLHttpRequest or Fetch API.

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.

Example of AJAX Using XMLHttpRequest

function loadData() {

var xhr = new XMLHttpRequest();

xhr.open("GET", "data.txt", true);

xhr.onreadystatechange = function () {

if (xhr.readyState == 4 && xhr.status == 200) {

document.getElementById("content").innerHTML = xhr.responseText;

};

xhr.send();

Explanation:

• XMLHttpRequest is used to send an asynchronous GET request.

• 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")

.then(response => response.text())

.then(data => document.getElementById("content").innerHTML = data)

.catch(error => console.error("Error:", error));

Advantages of Fetch API over XMLHttpRequest:


Simpler and cleaner syntax.
Uses Promises, making it easier to handle asynchronous operations.

Applications of AJAX

• Live Search (e.g., Google Search Suggestions)

• Real-time Chat Applications

• Form Validation without Page Refresh

• Loading Data from Server Without Refresh (e.g., News Feeds, Weather Updates)

• Auto-Saving Data (Google Docs, Online Forms, etc.)

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

var xhr = new XMLHttpRequest();

xhr.open("GET", "https://example.com/api/data", true); // true for async


xhr.onreadystatechange = function () {

if (xhr.readyState === 4 && xhr.status === 200) {

console.log(xhr.responseText); // Process the response

};

xhr.send();

XHR Methods

• open(method, url, async): Initializes the request.

• send(body): Sends the request.

• setRequestHeader(header, value): Sets HTTP request headers.

• abort(): Cancels the request.

XHR Properties

• readyState: Tracks request status (0-4).

• status: HTTP status code (e.g., 200 for success).

• responseText: Response as text.

• responseXML: Response as XML.

POST Request Example

var xhr = new XMLHttpRequest();

xhr.open("POST", "https://example.com/api/submit", true);

xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {

if (xhr.readyState === 4 && xhr.status === 200) {

console.log(xhr.responseText);
}

};

var data = JSON.stringify({ username: "John", age: 30 });

xhr.send(data);

Limitations & Modern Alternative

• XHR is old and somewhat cumbersome.

• Fetch API is preferred in modern JavaScript.

• XHR does not support promises.

AJAX (Asynchronous JavaScript and XML) with XML

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.

1. Using XMLHttpRequest with XML

This example fetches an XML response and processes it.

Example: Fetch XML Data from a Server

var xhr = new XMLHttpRequest();

xhr.open("GET", "https://example.com/data.xml", true);

xhr.onreadystatechange = function () {

if (xhr.readyState === 4 && xhr.status === 200) {

var xmlDoc = xhr.responseXML; // Parse XML response

var items = xmlDoc.getElementsByTagName("item");

for (var i = 0; i < items.length; i++) {

console.log(items[i].getElementsByTagName("name")[0].textContent);
}

};

xhr.send();

• responseXML gives the XML document.

• getElementsByTagName() extracts specific elements.

2. Sample XML File (data.xml)

<items>

<item>

<name>Product 1</name>

<price>100</price>

</item>

<item>

<name>Product 2</name>

<price>150</price>

</item>

</items>

3. Sending XML Data with POST Request

var xhr = new XMLHttpRequest();

xhr.open("POST", "https://example.com/api/upload", true);

xhr.setRequestHeader("Content-Type", "application/xml");
xhr.onreadystatechange = function () {

if (xhr.readyState === 4 && xhr.status === 200) {

console.log("Response:", xhr.responseText);

};

var xmlData = `<user><name>John</name><age>30</age></user>`;

xhr.send(xmlData);

• This sends XML data to the server.

4. Alternative: Fetch API with XML

fetch("https://example.com/data.xml")

.then(response => response.text())

.then(str => new window.DOMParser().parseFromString(str, "text/xml"))

.then(xml => {

let items = xml.getElementsByTagName("item");

for (let i = 0; i < items.length; i++) {

console.log(items[i].getElementsByTagName("name")[0].textContent);

})

.catch(error => console.error("Error fetching XML:", error));

• Fetch API is a modern approach and preferred over XMLHttpRequest.


Implementing Web APIs and Third-Party APIs

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).

1. Creating a Web API with Django

Since you're working with Django, here’s how you can build a simple REST API using Django
without Django REST Framework (DRF).

Step 1: Install Django

pip install django

Step 2: Create a Django Project

django-admin startproject myapi

cd myapi

python manage.py startapp api

Step 3: Define Models (models.py)

from django.db import models

class Product(models.Model):

name = models.CharField(max_length=100)

price = models.FloatField()

Step 4: Create a Simple API View (views.py)

import json

from django.http import JsonResponse

from .models import Product

def get_products(request):
products = list(Product.objects.values()) # Convert queryset to list

return JsonResponse(products, safe=False)

def add_product(request):

if request.method == "POST":

data = json.loads(request.body)

product = Product.objects.create(name=data['name'], price=data['price'])

return JsonResponse({"message": "Product added", "id": product.id})

Step 5: Define URL Patterns (urls.py)

from django.urls import path

from .views import get_products, add_product

urlpatterns = [

path('products/', get_products),

path('add-product/', add_product),

Step 6: Run the Server

python manage.py runserver

Now, you can send requests to:

• GET /products/ → Fetch all products

• POST /add-product/ → Add a new product

2. Consuming Third-Party APIs in JavaScript

Example: Fetch Weather Data from OpenWeather API


const apiKey = "YOUR_API_KEY";

const city = "New York";

fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error("Error fetching weather data:", error));

• Replace YOUR_API_KEY with your API key.

• Uses Fetch API for calling external APIs.

3. Consuming APIs in Django (Third-Party API Integration)

You can fetch data from an external API inside Django using requests.

Example: Fetch Data from a Public API

import requests

from django.http import JsonResponse

def fetch_weather(request):

city = "New York"

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)

• Calls OpenWeather API and returns JSON 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.

Install HttpClient Module

ng add @angular/common/http

Use HttpClient in app.module.ts

import { HttpClientModule } from '@angular/common/http';

@NgModule({

imports: [ HttpClientModule ],

})

export class AppModule { }

Fetching Data in a Component

import { HttpClient } from '@angular/common/http';

import { Component, OnInit } from '@angular/core';

@Component({

selector: 'app-weather',

template: `<h1>Weather: {{ weather?.main?.temp }}°C</h1>`,

})

export class WeatherComponent implements OnInit {

weather: any;

constructor(private http: HttpClient) {}


ngOnInit() {

this.http.get('https://api.openweathermap.org/data/2.5/weather?q=NewYork&appid=YOUR_
API_KEY')

.subscribe(data => this.weather = data);

• Uses HttpClient to fetch data from an API.

• Displays the temperature in the template.

You might also like