Unit 5 WTD Question Bank 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

21PCS10 – Web Technology and Design

Unit 5 – Question Bank


VELAMMAL COLLEGE OF ENGINEERING AND TECHNOLOGY, MADURAI

DEPARTMENT OF INFORMATION TECHNOLOGY

21PCS10 – WEB TECHNOLOGY AND DESIGN

UNIT V XML AND AJAX

XML Basics – Structuring Data – XML Namespaces – DTD – XSLT transformation – Creating
AJAX Applications using XML Http Request Object and JSON

CO5: Construct web applications using XML and AJAX

Textbook: Deitel and Deitel and Nieto, ―Internet and World Wide Web - How to Program‖,
5th Edition, Prentice Hall, 2011.

Two Marks Questions:

1. Explain the xmlns attribute. (K2)

The XML-namespace reserved attribute xmlns is used to create two namespace


prefixes—text and image. Each namespace prefix is bound to a series of characters
called a Uniform Resource Identifier (URI) that uniquely identifies the namespace.
Document authors create their own namespace prefixes and URIs. A URI is a way to
identifying a resource, typically on the Internet. Two popular types of URI are
Uniform Resource Name (URN) and Uniform Resource Locator (URL).

2. What is a namespace prefix?

The text namespace prefix is used for elements file and description. The end tags
must also specify the namespace prefix text.

<text:directory

xmlns:text = "http://www.deitel.com/xmlns-text"

xmlns:image = "http://www.deitel.com/xmlns-

image">

apply namespace prefix image to the elements file, description and size. Attributes
do not require namespace prefixes (although they can have them), because each
attribute is already part of an element that specifies the namespace prefix. For
example, attribute filename is implicitly part of namespace text because its element
(i.e., file) specifies the text namespace prefix.
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
Specifying a Default Namespace

To eliminate the need to place namespace prefixes in each element, document


authors may specify a default namespace for an element and its children.

3. What are unique URIs?


21PCS10 – Web Technology and Design
Unit 5 – Question Bank
To ensure that namespaces are unique, document authors must provide unique
URIs. In this example, we use urn:deitel:textInfo and urn:deitel:imageInfo as URIs.
These URIs employ the URN scheme that is often used to identify namespaces.
Under this naming scheme, a URI begins with "urn:", followed by a unique series of
additional names separated by colons.

Another common practice is to use URLs, which specify the location of a file or a
resource on the Internet. For example, www.deitel.com is the URL that identifies the
home page of the Deitel & Associates website. Using URLs guarantees that the
namespaces are unique because the domain names (e.g., www.deitel.com) are
guaranteed to be unique.

4. What are xml vocabularies ?

XML allows authors to create their own tags to describe data precisely. People and
organizations in various fields of study have created many different kinds of XML for
structuring data. Some of these markup languages are: MathML (Mathematical
Markup Language), Scalable Vector Graphics (SVG), Wireless Markup Language
(WML), Ex- tensible Business Reporting Language (XBRL), Extensible User Interface
Language (XUL) and Product Data Markup Language (PDML). Two other examples of
XML vocabularies are W3C XML Schema and the Extensible Stylesheet Language
(XSL).

5. Explain about validating parser.

When an XML document references a DTD or a schema, some parsers (called


validating parsers) can read it and check that the XML document follows the
structure it defines. If the XML document conforms to the DTD/schema (i.e., has the
appropriate structure), the document is valid. However, it would still be well-formed,
because it follows proper XML syntax (i.e., it has one root element, each element
has a start tag and an end tag, and the elements are nested properly). By definition,
a valid XML document is well-formed. Parsers that cannot check for document
conformity against DTDs/schemas are non- validating parsers—they determine only
whether an XML document is well-formed, not whether it’s valid.

6. What is xsl?

Extensible Stylesheet Language (XSL) documents specify how programs are to


render XML document data. XSL is a group of three technologies—XSL-FO (XSL
Formatting Objects), XPath (XML Path Language) and XSLT (XSL Transformations).
XSL-FO is a vocabulary for specifying formatting, and XPath is a string-based
language of expressions used by XML and many of its related technologies for
effectively and efficiently locating structures and data (such as specific elements and
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
attributes) in XML documents.

The third portion of XSL—XSL Transformations (XSLT)—is a technology for trans-


forming XML documents into other documents—i.e., transforming the structure of
the XML document data to another structure. XSLT provides elements that define
rules for
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
transforming one XML document to produce a different XML document. This is
useful when you want to use data in multiple applications or on multiple platforms,
each of which may be designed to work with documents written in a particular
vocabulary.

7. Define doc type.

The DOCTYPE reference <!DOCTYPE letter SYSTEM "letter.dtd"> contains three


items: the name of the root element that the DTD specifies (letter); the keyword
SYSTEM (which denotes an external DTD—a DTD declared in a separate file, as
opposed to a DTD declared locally in the same file); and the DTD’s name and
location (i.e., letter.dtd in the current directory; this could also be a fully qualified
URL). DTD document filenames typically end with the .dtd extension.

8. What is an xml namespace?

XML allows document authors to create custom elements. This extensibility can
result in naming collisions among elements in an XML document that have the same
name. For example, we may use the element book to mark up data about a Deitel
publication. A stamp collector may use the element book to mark up data about a
book of stamps. Using both of these elements in the same document could create a
naming collision, making it difficult to determine which kind of data each element
contains.

An XML namespace is a collection of element and attribute names. XML


namespaces provide a means for document authors to unambiguously refer to
elements with the same name (i.e., prevent collisions). For example,

<subject>Geometry</subject>

And

<subject>Cardiology</subject>

use element subject to mark up data. In the first case, the subject is something one
studies in school, whereas in the second case, the subject is a field of medicine.
Namespaces can differentiate these two subject elements—for example:
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
<highschool:subject>Geometry</highschool:subject>
and

<medicalschool:subject>Cardiology</medicalschool:subject>

Both highschool and medical school are namespace prefixes.

9. Explain about DTD.


21PCS10 – Web Technology and Design
Unit 5 – Question Bank
Document Type Definitions (DTDs) are one of two main types of documents you can
use to specify XML document structure. A DTD describes the structure of an XML
document and enables an XML parser to verify whether an XML document is valid
(i.e., whether its elements contain the proper attributes and appear in the proper
sequence). DTDs allow users to check document structure and to exchange data in a
standardized format. A DTD expresses the set of rules for document structure using
an EBNF (Extended Backus-Naur Form) grammar. DTDs are not themselves XML
documents.

10. List the XSL style sheet elements.

11. What is JSON?

JSON (JavaScript Object Notation)—a simple way to represent JavaScript objects as


strings—is a simpler alternative to XML for passing data between the client and the
server. Each object in JSON is represented as a list of property names and values
contained in curly braces, in the following format:

{ "propertyName1" : value1, "propertyName2": value2 }

Arrays are represented in JSON with square brackets in the following

format: [ value1, value2, value3 ]

Each value can be a string, a number, a JSON representation of an object, true, false
or null. You can convert JSON strings into JavaScript objects with JavaScript’s
JSON.parse function. JSON strings are easier to create and parse than XML and
require fewer bytes. For these reasons, JSON is commonly used to communicate in
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
client/server interaction.

12. How will u parse a JSON data?

1 [ { "first": "Cheryl", "last": "Black" },

2 { "first": "James", "last": "Blue" },


21PCS10 – Web Technology and Design
Unit 5 – Question Bank
3 { "first": "Mike", "last": "Brown" },

4 { "first": "Meg", "last": "Gold" } ]

When the XMLHttpRequest object receives the response, it calls function

parseData function parseData( asyncRequest )

// if request has completed successfully, process the response

if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 )

// convert the JSON string to an Object

var data =

JSON.parse(asyncRequest.responseText);

displayNames( data ); // display data on the page

} // end if

} // end function parseData

Line 53 var data = JSON.parse(asyncRequest.responseText); calls the


JSON.parse function, which converts the JSON string into a JavaScript object. Then
line displayNames( data ); calls function displayNames, which displays the first and
last name of each address-book entry passed to it. Lines

var listBox = document.getElementById( "Names"

); listBox.innerHTML = "";

use the HTML5 DOM to store the placeholder div element Names in the variable
listbox and clear its content. Once parsed, the JSON string of address-book entries
becomes an array, which this function traverses.

13. What is AJAX?

AJAX - Asynchronous JavaScript and XML.

A new technique for creating better, faster, and more interactive web applications
with the help of XML, HTML, CSS, and Java Script.
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
Ajax uses

XHTML for content

CSS for

presentation

Document Object Model and JavaScript for dynamic content display.


21PCS10 – Web Technology and Design
Unit 5 – Question Bank
14. How will you define empty elements in a DTD?

<!ELEMENT flag EMPTY> defines an empty element named flag. Keyword EMPTY
specifies that the element does not contain any data between its start and end tags.
Empty elements commonly describe data via attributes. For example, flag’s data
appears in its gender attribute (<!ATTLIST flag gender (M | F) "M">). <!ATTLIST flag
gender (M | F) "M"> specifies that the gender attribute’s value must be one of the
enumerated values (M or F) enclosed in parentheses and delimited by a vertical
bar (|) meaning ―or.‖ <!ATTLIST flag gender (M | F) "M"> also indicates that
gender has a default value of M.

15. Explain about templates in XSLT.

XSLT uses templates (i.e., xsl:template elements) to describe how to transform


particular nodes from the source tree to the result tree. A template is applied to
nodes that are specified in the required match attribute. 10 <xsl:template match =
"/"> <!-- match root element --> uses the match attribute to select the document
root (i.e., the conceptual part of the document that contains the root element and
everything below it) of the XML source document (i.e., sports.xml). The XPath
character / (a forward slash) always selects the document root. Recall that XPath is a
string-based language used to locate parts of an XML document easily. In XPath, a
leading forward slash specifies that we’re using absolute addressing (i.e., we’re
starting from the root and defining paths down the source tree).

PART B & C

1. Explain the XSLT transformation process that produces a single result XML
document given an XSLT document and a source XML document (K2)

XSLT (Extensible Stylesheet Language Transformations) is a language used for


transforming XML documents into other XML documents or formats. The XSLT
transformation process involves applying an XSLT stylesheet to an XML source
document to generate a new XML document or other output formats (such as HTML,
text, etc.). Here's an overview of the XSLT transformation process:

1. XSLT Document (Stylesheet):


- An XSLT document (also called an XSLT stylesheet) contains instructions written in
XSLT language.
- It defines rules, templates, and transformations to be applied to the source XML
document.
- The XSLT document specifies how elements from the source XML should be
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
transformed into the desired output format.

2. Source XML Document:


- The source XML document contains the data to be transformed.
- It provides the structured data that will be used as the basis for transformation.

3. XSLT Transformation Process:


- Parsing: The XSLT processor reads and parses the XSLT stylesheet and the source
XML document.
- Matching and Transformation: The XSLT processor applies the rules defined in the
XSLT document to the corresponding elements in the source XML document.
- Template Matching: The processor matches templates in the XSLT stylesheet to
elements in the source XML based on rules like element names, attributes, or
patterns.
- Applying Templates: When a match occurs, the XSLT processor applies the specified
transformation logic defined in the matched template to generate the output.
- Output Generation: The transformation process creates a new XML document or
another output format based on the defined transformations and logic in the XSLT
stylesheet.

4. Producing a Single Result XML Document:


- As the XSLT processor processes the source XML and applies the transformations, it
generates a new XML document by assembling the transformed elements according
to the rules defined in the XSLT stylesheet.
- The output document typically combines selected data from the source XML
document in a format defined by the XSLT transformations.

Example:
Suppose you have an XSLT stylesheet that transforms an XML document containing
book information into an HTML table. The XSLT document defines templates for
matching book elements and transforming them into HTML table rows and columns.

```xml
<!-- Sample XML (source document) -->
<library>
<book>
<title>Book 1</title>
<author>Author 1</author>
</book>
<book>
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
<title>Book 2</title>
<author>Author 2</author>
</book>
</library>
```

```xslt
<!-- XSLT Stylesheet -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr>
<th>Title</th>
<th>Author</th>
</tr>
<xsl:apply-templates select="library/book"/>
</table>
</body>
</html>
</xsl:template>

<xsl:template match="book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
```

When the XSLT processor applies this stylesheet to the provided XML, it transforms the
book elements into an HTML table, producing a single result document that presents
book information in table format.

The result of an XSLT transformation is a new XML document or another format that
represents the transformed data based on the rules and transformations specified in
the XSLT stylesheet.

2. Explain about how to create a Full-Scale Ajax-Enabled Application using JSON (K2)
21PCS10 – Web Technology and Design
Unit 5 – Question Bank

Creating a full-scale Ajax-enabled application using JSON involves leveraging the power of
Asynchronous JavaScript and XML (Ajax) along with JSON (JavaScript Object Notation) to
facilitate data exchange between the client and server. Here are the steps to create such
an application:

1. Setup Frontend (HTML/CSS/JavaScript):

HTML Structure:

Create an HTML structure that includes elements for user interface components. For
instance, forms, buttons, tables, etc., that will interact with the backend via Ajax.

JavaScript (Ajax):

1. Event Listeners: Attach event listeners (e.g., click events) to the HTML elements that will
trigger Ajax requests.

2. Ajax Requests: Use JavaScript's `XMLHttpRequest` or higher-level methods like `fetch` or


libraries like Axios or jQuery's `$.ajax` to make asynchronous requests to the server.

3. Handling Responses: Handle the responses from the server, parse JSON data (if received),
and update the DOM dynamically to reflect the changes.

2. Backend Implementation (Server-side):

Server-Side Scripting (PHP/Node.js/Python/Ruby, etc.):

1. Endpoints: Create server-side endpoints (API routes or functions) that respond to Ajax
requests.

2. Data Processing: Implement logic to process incoming requests, interact with databases,
perform calculations, or any other backend operation required.

3. Response: Return JSON-formatted data as a response to Ajax requests.

3. JSON (Data Format):

Data Interchange Format:


21PCS10 – Web Technology and Design
Unit 5 – Question Bank
1. Serialization: Convert server-side data (objects, arrays, etc.) into JSON format before
sending it to the client.

2. Parsing: Parse JSON responses received from the server on the client-side to extract and
utilize the data.

4. Integration of Ajax and JSON:

Data Exchange:

1. Request Payload: Send JSON-formatted data as part of Ajax requests (either as request
parameters or in the request body).

2. Response Handling: Parse JSON responses received from the server and use the data to
update the user interface dynamically.

Example Workflow:

Frontend:

1. User interacts with the UI component (e.g., submits a form).

2. JavaScript triggers an Ajax request to the server, sending data in JSON format.

3. Backend processes the request, performs operations, and returns a JSON response.

4. Frontend JavaScript parses the JSON response and updates the UI accordingly.

Backend:

1. Receives Ajax requests from the frontend.

2. Processes data, performs required operations, and prepares a JSON response.

3. Sends the JSON response back to the frontend.

Tips:

- Ensure proper error handling for Ajax requests and responses.

- Use appropriate HTTP methods (GET, POST, PUT, DELETE) for different types of operations.

- Validate user inputs both on the client-side and server-side to prevent security
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
vulnerabilities.

By leveraging Ajax for asynchronous communication and using JSON as the data format,
you can create responsive and interactive web applications with seamless data exchange
between the client and server.

3. Explain in detail about xml namespaces with example. (K2)

XML namespaces are used in XML documents to avoid element name conflicts and to
differentiate elements that might have the same name but belong to different
vocabularies or sources. They provide a way to uniquely identify elements and attributes
within an XML document or between different XML documents.

Basic Concepts:

1. Namespace Declaration:
- Namespaces are declared using the `xmlns` attribute in XML elements.
- The `xmlns` attribute assigns a unique identifier (namespace URI) to a namespace prefix.
- It is common to use the `xmlns` attribute in the root element of an XML document.

2. Namespace Prefixes:
- Prefixes (e.g., `x`, `html`, `svg`) are used to associate elements and attributes with a
specific namespace.
- They are followed by a colon (`:`) in element and attribute names.

3. Namespace URI (Uniform Resource Identifier):


- A Namespace URI is a unique identifier used to distinguish one namespace from another.
- It can be a URL, URN, or any other string as long as it provides a unique identification.

Example:

Consider an example where we have two XML vocabularies: a bookstore and a library. We'll
use namespaces to differentiate elements from these vocabularies:

```xml
<!-- XML document using namespaces -->
<library:books xmlns:library="http://example.com/library">
<book>Book 1 from Library</book>
</library:books>

<bookstore:books xmlns:bookstore="http://example.com/bookstore">
<book>Book 1 from Bookstore</book>
</bookstore:books>
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
```

Explanation:

- In the above example, `<library:books>` and `<bookstore:books>` are root elements


belonging to different namespaces.
- The prefixes `library` and `bookstore` are defined using `xmlns` attributes to associate
these elements with their respective namespaces.
- Elements `<book>` inside each namespace have different meanings based on their parent
namespace.

Usage in XPath and XSLT:

When working with XPath or XSLT, namespaces need to be considered for proper element
selection and transformations:

XPath:
```xpath
//library:books/book <!-- Selects book elements within the library namespace -->
```

XSLT:
```xml
<xsl:template match="library:books">
<!-- XSLT template to process elements within the library namespace -->
</xsl:template>
```

Benefits of Namespaces:

1. Avoiding Name Conflicts: Prevents clashes between elements with the same name from
different sources.
2. Modularity: Enables mixing elements from different vocabularies within a single
document.
3. Interoperability: Facilitates exchange of XML data between different systems and
applications.

4. Explain in detail about Document type declaration (K2)

A Document Type Declaration (DTD) is an optional but essential part of an XML document
that defines the structure, elements, entities, and their relationships within the
document. It essentially serves as a set of rules or a schema that specifies the valid
elements, attributes, and their organization in an XML document. Here's an in-depth
explanation of DTD:
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
Purpose of DTD:

1. Defining Document Structure:


- DTD defines the structure of an XML document by specifying the elements, their order,
nesting, and attributes allowed within the document.

2. Ensuring Validity:
- It ensures that the XML document conforms to a predefined structure, helping maintain
consistency and validity.

3. Enabling Interoperability:
- DTD facilitates data exchange between systems by establishing a common set of rules for
document structure.

Components of DTD:

1. Element Declarations:
- Defines the elements that can appear in the document.
- Specifies the element names, their content models (such as EMPTY, ANY, or specific
content), and occurrence constraints.

```xml
<!ELEMENT element_name (child_element)>
```

2. Attribute Declarations:
- Defines the attributes associated with specific elements.
- Specifies the attribute names, their types, and default or fixed values.

```xml
<!ATTLIST element_name attribute_name attribute_type default_value>
```

3. Entity Declarations:
- Defines entities (variables) that can be referenced within the document.
- Entities can represent text strings, special characters, or reusable content.

```xml
<!ENTITY entity_name "entity_value">
```

4. Notation Declarations:
- Specifies notations for non-XML data, such as images or multimedia content.
- Defines the format or application associated with specific data types.

```xml
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
<!NOTATION notation_name SYSTEM "system_identifier">
```

Example of a Simple DTD:

Consider an XML document representing a list of books. A simple DTD for this XML might
look like this:

```xml
<!DOCTYPE bookstore [
<!ELEMENT bookstore (book+)>
<!ELEMENT book (title, author, year)>
<!ELEMENT title (PCDATA)>
<!ELEMENT author (PCDATA)>
<!ELEMENT year (PCDATA)>
]>
```

- `<!DOCTYPE>` declares the document type and associates it with the DTD.
- Inside the square brackets (`[]`) is the DTD definition.
- `<!ELEMENT>` defines the structure of elements and their content.
- `(PCDATA)` denotes parsed character data (text content).

Integrating DTD into XML Document:

To use the DTD within an XML document, you include a `DOCTYPE` declaration at the
beginning of the XML file, referencing the DTD file or defining the DTD structure directly
within the document:

```xml
<!DOCTYPE root_element_name SYSTEM "path/to/dtd_file.dtd">
<!-- XML content -->
<root_element_name>
<!-- Elements and content -->
</root_element_name>
```

Advantages of DTD:

- Validation: Ensures the correctness and consistency of the XML document structure.
- Interoperability: Enables data exchange between systems by adhering to a common
structure.
- Reusability: Allows the reuse of entities and definitions across multiple XML documents.

5. Explain in detail about XSLT. (K2)


21PCS10 – Web Technology and Design
Unit 5 – Question Bank

XSLT (Extensible Stylesheet Language Transformations) is a language for transforming XML


documents into other XML documents, HTML, text, or other formats. It's a powerful tool
for converting and presenting XML data in various ways. Here's an in-depth explanation
of XSLT:

Key Components of XSLT:

1. XSLT Processor:
- XSLT processors interpret XSLT stylesheets and apply transformations to XML documents.
- Browsers, programming languages (like Java, Python), or dedicated XSLT processors (such
as Xalan, Saxon) can execute XSLT transformations.

2. XSLT Stylesheets:
- XSLT stylesheets contain instructions for transformations.
- Written in XML syntax and comprise templates and rules to define how XML elements
should be transformed into other formats.

Basic Syntax Elements:

a. Templates:
- Define rules for transforming specific elements or patterns in the XML document.
- Written using `<xsl:template>` elements.

```xml
<xsl:template match="book">
<!-- Transformation logic -->
</xsl:template>
```

b. XPath Expressions:
- Used to navigate and select nodes in the XML document.
- Allows filtering, selecting, and manipulating nodes.

```xml
<xsl:value-of select="title"/>
```

c. Output Elements:
- Control the output structure and format.
- For example, `<xsl:element>`, `<xsl:attribute>`, `<xsl:value-of>`.

Example of XSLT Transformation:

Consider a simple XML document representing a list of books and an XSLT stylesheet to
transform this XML into an HTML table:
21PCS10 – Web Technology and Design
Unit 5 – Question Bank

XML (books.xml):
```xml
<library>
<book>
<title>Book 1</title>
<author>Author 1</author>
</book>
<book>
<title>Book 2</title>
<author>Author 2</author>
</book>
</library>
```

XSLT (transform.xslt):
```xml
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Book List</h2>
<table border="1">
<tr>
<th>Title</th>
<th>Author</th>
</tr>
<xsl:apply-templates select="library/book"/>
</table>
</body>
</html>
</xsl:template>

<xsl:template match="book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
```

Transformation Process:

1. Loading XML and XSLT:


- The XML document and XSLT stylesheet are loaded into the XSLT processor.
21PCS10 – Web Technology and Design
Unit 5 – Question Bank

2. Matching Templates:
- The processor begins at the root template (`<xsl:template match="/">`) and executes
instructions accordingly.

3. Applying Templates:
- The `<xsl:apply-templates>` instruction selects and applies matching templates
(`<xsl:template match="book">`) to elements in the XML.

4. Generating Output:
- The transformation generates an HTML output based on the rules defined in the XSLT
stylesheet.

Advantages of XSLT:

1. Flexible Transformations: Allows complex transformations and manipulations of XML


data.
2. Standardization: Conforms to W3C standards, ensuring interoperability.
3. Separation of Concerns: Separates content from presentation, facilitating easier
maintenance and updates.

XSLT is a powerful language for transforming XML data into various formats, making it an
essential tool for generating dynamic content, reports, or formatting XML data for display
on web pages or in different applications.

6. Develop XSLT code to display employee details in a Table from which is stored is
XML. (K3)

XSLT code that transforms an XML document containing employee details into an HTML
table format:

XML Document (employees.xml):


Assuming an XML structure like this:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee>
<id>1</id>
<name>John Doe</name>
<department>IT</department>
</employee>
<employee>
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
<id>2</id>
<name>Jane Smith</name>
<department>HR</department>
</employee>
<!-- Other employee details -->
</employees>
```

XSLT (transform_employees.xslt):
```xml
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>Employee Details</h2>
<table border="1">
<tr bgcolor="9acd32">
<th>ID</th>
<th>Name</th>
<th>Department</th>
</tr>
<xsl:for-each select="employees/employee">
<tr>
<td><xsl:value-of select="id"/></td>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="department"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>
```

Explanation:
- The XSLT code defines a template that matches the root node of the XML document
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
(`<xsl:template match="/">`).
- It generates an HTML table with a header row (`<th>`) and iterates through each
`<employee>` element in the XML using `<xsl:for-each>`.
- For each employee, it extracts the `<id>`, `<name>`, and `<department>` values and
populates them in respective table cells (`<td>`).
- The resulting output will be an HTML table displaying employee details.

7. Develop a XML program to store voter ID, voter name, address and date of birth
details. Create a DTD to validate the document. (K3)

XML document that stores voter details (voter ID, name, address, and date of birth) along
with a corresponding DTD (Document Type Definition) to validate the structure of the
XML document:

XML Document (voter_details.xml):

```xml

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

<!DOCTYPE voters SYSTEM "voter_details.dtd">

<voters>

<voter>

<voterID>V123456789</voterID>

<name>John Doe</name>

<address>123 Main Street, City</address>

<dob>1990-05-15</dob>

</voter>

<voter>

<voterID>V987654321</voterID>

<name>Jane Smith</name>

<address>456 Park Avenue, Town</address>

<dob>1985-08-25</dob>
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
</voter>

<!-- Other voter details -->

</voters>

```

DTD (voter_details.dtd):

```xml

<!ELEMENT voters (voter+)>

<!ELEMENT voter (voterID, name, address, dob)>

<!ELEMENT voterID (PCDATA)>

<!ELEMENT name (PCDATA)>

<!ELEMENT address (PCDATA)>

<!ELEMENT dob (PCDATA)>

```

Explanation:

- The XML document `voter_details.xml` contains voter details structured as `<voters>`


containing multiple `<voter>` elements.

- Each `<voter>` element includes child elements for `voterID`, `name`, `address`, and
`dob` (date of birth).

- The `DOCTYPE` declaration references the DTD file (`voter_details.dtd`) for validation.

- The DTD (`voter_details.dtd`) defines the structure of the XML document:

- `<voters>` can have one or more `<voter>` elements (`<!ELEMENT voters (voter+)>`).

- `<voter>` elements must contain `voterID`, `name`, `address`, and `dob` elements
(`<!ELEMENT voter (voterID, name, address, dob)>`).

- `voterID`, `name`, `address`, and `dob` are defined as elements containing parsed
character data (`<!ELEMENT voterID (PCDATA)>`, `<!ELEMENT name (PCDATA)>`, etc.).
21PCS10 – Web Technology and Design
Unit 5 – Question Bank

To validate `voter_details.xml` against the provided DTD, you would need to


reference the DTD file (`voter_details.dtd`) in your XML processor. This validation
ensures that the XML document adheres to the specified structure defined in the DTD.

8. Develop an AJAX application using XMLHttpRequest object and JSON. (K3)

AJAX application using the `XMLHttpRequest` object to fetch data in JSON format from a
server and display it on a web page.

HTML (index.html):

Create an HTML file with a button to trigger the AJAX request and a `<div>` to display the
fetched data.

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>AJAX Application with JSON</title>

<script>

function fetchData() {

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {

if (xhr.readyState === XMLHttpRequest.DONE) {

if (xhr.status === 200) {

var response = JSON.parse(xhr.responseText);

document.getElementById('output').innerHTML = JSON.stringify(response, null,


2);

} else {

document.getElementById('output').innerHTML = 'Error fetching data';


21PCS10 – Web Technology and Design
Unit 5 – Question Bank
}

};

xhr.open('GET', 'data.json', true);

xhr.send();

</script>

</head>

<body>

<button onclick="fetchData()">Fetch Data</button>

<div id="output"></div>

</body>

</html>

```

JSON (data.json):

Create a file named `data.json` containing sample JSON data.

```json

"id": 1,

"name": "John Doe",

"age": 30,

"email": "[email protected]"

},

{
21PCS10 – Web Technology and Design
Unit 5 – Question Bank
"id": 2,

"name": "Jane Smith",

"age": 25,

"email": "[email protected]"

```

Explanation:

- The HTML file contains a button (`<button onclick="fetchData()">Fetch Data</button>`)


that triggers the `fetchData()` function on click.

- The JavaScript function `fetchData()` creates an `XMLHttpRequest` object, sets up an


asynchronous GET request to fetch `data.json`, and handles the response.

- The `onreadystatechange` event listener monitors the state changes of the request.

- When the request is complete (`readyState === XMLHttpRequest.DONE`) and successful


(`status === 200`), the response (JSON data) is parsed and displayed inside the `<div
id="output">`.

- If there's an error in fetching data, an error message is displayed in the same `<div>`.

Ensure that the `data.json` file is placed in the same directory as the HTML file for this
example to work properly. This code demonstrates a basic AJAX application using
`XMLHttpRequest` to fetch JSON data and display it on a web page when a button is
clicked.

You might also like