0% found this document useful (0 votes)
30 views35 pages

WT U3 Key

This is unit 3 of web tech

Uploaded by

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

WT U3 Key

This is unit 3 of web tech

Uploaded by

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

WEB TECHNOLOGY

UNIT III
PART B
1. (i) List and explain the XML syntax rules in detail. (7)
The basic XML syntax rules are as follows (these are covered only briefly
here, since they all should be familiar from our earlier study of XHTML):

 An XML document consists of markup and character data.


 There are two types of markup: tags and references.
 Tags begin with a less-than (<) character and end with a greater-than (>) character.
References in an XML document begin with an ampersand (&) and are of two types:
character references (such as &#x20;) and entity references (such as &lt;).
 All XML documents may make references to the entities lt, gt, amp, apos, and quot,
which map to the characters less than (<), greater than (>), ampersand (&), single quote ('),
and double quote ("), respectively. Other entities may also be defined, depending on the
XML DTD used and/or application processing the document.
 If not used to begin markup, the characters < and & must be escaped (an exception is
that escaping is not necessary within comments and CDATA sections; see the remarks
following this list).
 Element tags are of three types: start tags, end tags (which begin with </), and
emptyelement tags (which end with />).
 Character data may only appear within a nonempty element. Start and end tags must be
paired and must be properly nested with other pairs of start and end tags.
 Attribute specifications may appear within start tags or empty-element tags. Every
attribute specification consists of an attribute name followed by an equals sign (=) followed
by a quoted attribute value. An attribute value may not contain the character <; if the
character & appears, it must be the first character in a character or entity reference. A pair
of either single quotes or double quotes may be used to quote an attribute value. Attribute
specifications are white-space-separated from one another.
 Element and attribute names are case sensitive.
 The XML white space characters are the same as in XHTML (Table 2.1): space, carriage
return, line feed, and tab.
 XML comments begin with <!--, end with -->, and may not contain the string --elsewhere
within the content of the comment

(ii) Explain how XML document can be displayed on a browser.(6)


An XML document can be viewed using a simple text editor or any browser. Most of the
major browsers supports XML. XML files can be opened in the browser by just double-
clicking the XML document (if it is a local file) or by typing the URL path in the address bar (if
the file is located on the server), in the same way as we open other files in the browser. XML
files are saved with a ".xml" extension.
 Web browsers also offer various levels of support for XML processing. Because such
browser support is not uniform and this capability does not seem to be in
widespread use on the Web at this time, I will cover browser support for XML only
briefly here.
 First, there is a standard mechanism for associating style information (either CSS or
XSLT) with XML documents via an XML processing instruction.
 A processing instruction is a special XML tag that has a syntax similar to that of an
XML declaration: the tag begins with <? and ends with ?>.
 Semantically, a processing instruction is viewed by an XML application as an
instruction to the application itself rather than as part of the markup and character
data contained in the document. Each processing instruction begins with a name
known as the target of the processing instruction and may contain other character
data as well.
 The processing instruction used to associate style information with an XML
document has target xml-stylesheet.
The “attributes” in a processing instruction are referred to as pseudo-attributes.
If the XSLT document of Figure 7.12 is located at the URL HelloWorld.xsl, then if either
Mozilla 1.4 or IE6 loads the XML document of Figure 7.28, the browser will apply the XSLT
document to the XML document and then display the resulting XHTML document as if it
had been loaded into the browser rather than the XML document. The final result in
Mozilla is shown in Figure 7.29; by looking at the browser title bar, you can tell that the
browser is not simply displaying the character data from the XML document. If you were to
view the source of the document, however, you would see only the original XML document,
not the generated XHTML.
Alternatively, a CSS style sheet can be applied to an XML document using the xml-
stylesheet processing instruction. For example, if HelloWorld.css is a URL for the style
sheet /* HelloWorld.css */ message { display: block; margin: 8px; font-weight: bolder } and
the XML document Hello World! is loaded into Mozilla 1.4, then the browser will style the
XML document as shown in Figure 7.30

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


<xsl:transform version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:template match="/">
<html>
<head>
<title>
HelloWorld.xsl (transformed)
</title>
</head>
<body>
<p><xsl:value-of select="child::message" /></p>
</body>
</html>
</xsl:template>
</xsl:transform>
FIGURE 7.12 An example XSL document HelloWorld.xsl

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


<!-- HelloWorldStyled.xml -->
<?xml-stylesheet type="text/xsl" href="HelloWorld.xsl"?>
<message>Hello World!</message>
FIGURE 7.28 XML document containing an xml-stylesheet processing instruction that
associates the XML document with an XSLT document.

FIGURE 7.29 Browser rendering of XML document from Figure 7.28 after XSLT
transformation has been applied

FIGURE 7.30 Browser rendering of XML document styled using CSS

2. (i) Explain the role of XML name spaces with examples. (7)
An XML vocabulary is created by specifying a complete description of the elements
and attributes for a specific type of XML document. (An XML vocabulary is also
sometimes referred to as an XML application)
 TheW3C’s XML Namespace recommendation [W3C-XML-NAMESPACE-1.1]
provides a mechanism for identifying each element and attribute name
within a document with a specific XML vocabulary. An XML namespace is a
collection of element and attribute names associated with a particular XML
vocabulary (such as XHTML) through an absolute URI known as the
namespace name.
 An example namespace name is http://www.w3.org/1999/xhtml, which is
specified as the namespace name for XHTML 1.0 by its recommendation
[W3C-XHTML-1.0]. We have seen this namespace name frequently in earlier
examples. In fact, XHTML 1.0 requires that every XHTML document be
associated with this namespace name by including an xmlns attribute
specification in the root element of the document:
<html xmlns="http://www.w3.org/1999/xhtml">
 The meaning of the xmlns attribute is defined by the XML Namespace
recommendation.
When specified on a root element as shown, the xmlns attribute specifies a default
namespace for the entire document. So, in an XHTML document, the xmlns
specification indicates that all element type names within the document—including
html—belong by default to the XML namespace having namespace name
http://www.w3.org/1999/xhtml. Specifying a default namespace has no effect on
attributes, which belong to no namespace unless explicitly associated with a
namespace via mechanisms
 Embedded elements, such as XHTML elements within an RSS document,
First, the document must associate a namespace prefix with the namespace
containing the embedded element types. This is done using a special form of
the xmlns attribute. For example, in an RSS document we might associate
the namespace prefix xhtml with the namespace name
http://www.w3.org/1999/xhtml as follows:
<rss version="0.91" xmlns:xhtml="http://www.w3.org/1999/xhtml">
An xmlns attribute specification of this form is called a namespace declaration.
 Once a namespace has been associated with a namespace prefix through a
namespace declaration, we can mark any element (or attribute) name as
belonging to the namespace by preceding the name with the prefix. For
example, in an RSS document containing the given namespace declaration,
we can mark an a element as belonging to the XHTML namespace as follows
(notice that both the start and end tags contain the namespace prefix):
<item>
<title>Announcing a Sibling Site!</title>
<link>http://www.example.org/</link>
<description>Were you aware that
<xhtml:a href="example.com">example.com</xhtml:a>
is not the only site in the example family?</description>
</item>
 The XML namespace concept was defined some time after XML itself was initially
defined and, as we have noted, is covered in a separate W3C recommendation.
Therefore, some software may fully comply with the XML recommendation and yet
not be namespace aware. In software that is namespace-aware, all element and
attribute names (except for xmlns attributes) are referred to as qualified names,
whether or not they are prefixed.
 Associated with each qualified name is an expanded name, which is a pair
consisting of a namespace name and a local name. The local name is just the
qualified name with any namespace prefix removed;
 for example, in the qualified name xhtml:a , a is the local name. In typical Java
XML software, if a qualified name is not in any namespace, then the namespace-
name component of its expanded name is represented by null.

It should be noted that if you design an XML vocabulary and wish to conform with
the XML namespace recommendation, the element and attribute names you define
must not use colons (for obvious syntactic reasons). Similarly, an XML document
conforming with XML namespace may not contain colons in prefix names or in the
values specified for attributes of the XML data type ID

(ii) Explain the features of XML path language. (6)


XML Path Language (XPath), which defines the syntax and semantics of many of the
attribute values used in XSL elements for accessing portions of the input XML document;
XPath is a syntax for specifying a collection of elements or other information contained
within an XML document. I will describe version 1.0 of XPath [W3C-XPATH-1.0], which
is the current version at the time of this writing.
Conceptually, XPath assumes that the XML document to which XPath expressions
will be applied has been parsed into an internal tree representation. The XPath tree model
is similar to the DOM tree. For example, the nodes in an XPath tree are of different types,
such as element, text, and comment nodes. In addition, unlike the DOM model, the XPath
tree model also uses nodes to represent attribute name value pairs.
The root of the XPath parse tree is known as the document root. Like an instance
of Document in the DOM, this node of the XPath parse tree has a child node representing
the root of the element hierarchy in the parsed document; this node is called the document
element. In Figure 7.13, the root element is of type message. Thus, for this example XML
document, an XPath element node of type message will be a child of the document root
node in the XPath parse tree.
<?xml version="1.0" encoding="UTF-8"?>
<message>Hello World!</message>
FIGURE 7.13 Simple XML document HelloWorld.xml to be transformed.

3.Write XSLT code to display employee details in a Table form which is stored is XML.
(13)
<?xml version = "1.0"?>
<class>
<employee id = "001">
<firstname>Aryan</firstname>
<lastname>Gupta</lastname>
<nickname>Raju</nickname>
<salary>30000</salary>
</employee>
<employee id = "024">
<firstname>Sara</firstname>
<lastname>Khan</lastname>
<nickname>Zoya</nickname>
<salary>25000</salary>
</employee>
<employee id = "056">
<firstname>Peter</firstname>
<lastname>Symon</lastname>
<nickname>John</nickname>
<salary>10000</salary>
</employee>
</class>

Define an XSLT stylesheet document for the above XML document. You
should follow the criteria give below:

o Page should have a title employee.


o Page should have a table of employee's details.
o Columns should have following headers: id, First Name, Last Name,
Nick Name, Salary
o Table must contain details of the employees accordingly.

Step1: Create XSLT document

Create the XSLT document which satisfies the above requirements. Name
it as employee.xsl and save it in the same location of employee.xml.

Employee.xsl

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


<!-- xsl stylesheet declaration with xsl namespace:
Namespace tells the xlst processor about which
element is to be processed and which is used for output purpose only
-->
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<!-- xsl template declaration:
template tells the xlst processor about the section of xml
document which is to be formatted. It takes an XPath expression.
In our case, it is matching document root element and will
tell processor to process the entire document with this template.
-->
<xsl:template match = "/">
<!-- HTML tags
Used for formatting purpose. Processor will skip them and browse
r
will simply render them.
-->
<html>
<body>
<h2>Employee</h2>
<table border = "1">
<tr bgcolor = "#9acd32">
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nick Name</th>
<th>Salary</th>
</tr>
<!-- for-each processing instruction
Looks for each element matching the XPath expression
-->
<xsl:for-each select="class/employee">
<tr>
<td>
<!-- value-of processing instruction
process the value of the element matching the XPath ex
pression
-->
<xsl:value-of select = "@id"/>
</td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
<td><xsl:value-of select = "nickname"/></td>
<td><xsl:value-of select = "salary"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Step2: List the XSLT document to the XML document

Update employee.xml document with the following xml-stylesheet tag. Set


href value to employee.xsl

<?xml version = "1.0"?>


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

Updated "employee.xml"

<?xml version = "1.0"?>


<?xml-stylesheet type = "text/xsl" href = "employee.xsl"?>
<class>
<employee id = "001">
<firstname>Aryan</firstname>
<lastname>Gupta</lastname>
<nickname>Raju</nickname>
<salary>30000</salary>
</employee>
<employee id = "024">
<firstname>Sara</firstname>
<lastname>Khan</lastname>
<nickname>Zoya</nickname>
<salary>25000</salary>
</employee>
<employee id = "056">
<firstname>Peter</firstname>
<lastname>Symon</lastname>
<nickname>John</nickname>
<salary>10000</salary>
</employee>
</class>

Step3: View the XML document in Internet Explorer

The output will look like this:

Output:
3. (i) Explain in detail about XSL.(7)
Different type of transformation, extracts information from one XML text document and
uses that information to create another XML text document.
The “programming language” used to direct this type of transformation is the Extensible
Stylesheet Language (XSL). XSL is an XML vocabulary; that is, XSL documents are well-
formed XML documents. So the transformation “program” is an XML document. An XSL
document normally contains two types of information: template data, which is text that is
copied to the output XML text document with little or no change; and XSL markup, which
controls the transformation process.

An example XSL document is shown in Figure 7.12. The first thing to notice is that
it uses two namespaces. http://www.w3.org/1999/XSL/Transform is the namespace name
for the XSL namespace, and of course http://www.w3.org/1999/xhtml is the XHTML
namespace name. So, in this document, XHTML is the default namespace, and elements
prefixed with xsl belong to the XSL namespace. Elements belonging to the XSL namespace
are part of the XSL “programming language” and direct the transformation, while elements
in other namespaces form part of the template data of the XSL document.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:template match="/">
<html>
<head>
<title>
HelloWorld.xsl (transformed)
</title>
</head>
<body>
<p><xsl:value-of select="child::message" /></p>
</body>
</html>
</xsl:template>
</xsl:transform>
FIGURE 7.12 An example XSL document HelloWorld.xsl

XSL actually is a collection of three separate W3C recommendations:


 XSL Transformations (XSLT), which defines the semantics of the various elements
and attributes of the XSL namespace;
 XML Path Language (XPath), which defines the syntax and semantics of many of the
attribute values used in XSL elements for accessing portions of the input XML
document;
 and XSL Formatting Objects (XSL-FO), a separate XML vocabulary for defining style
properties of an XML document.

(ii) Explain about DOM based XML processing. (6)


In DOM-based XML processing, an XML document is first input and parsed, creating
a tree of nodes representing elements, text, comments, and so on. After the tree has been
constructed, methods can be called to modify the tree, extract data from it, and so on.

The Java DOM API specifies a number of interfaces that correspond to DOM objects and
classes in the context of JavaScript, such as Node, Document.
Let’s consider the Java program of Figure 7.7. This program performs the following task:
input from a user-specified file an RSS document such as the one shown in Figure 7.1, and
output the number of link elements contained in the input document. So, for example, if the
example RSS document of Figure 7.1 was contained in a file named
ExampleContentFeed.xml and the Java program was named DOMCountLink, then a run of
the program might look like (user input is italicized)
$ java DOMCountLinks ExampleContentFeed.xml
Input document has 3 'link' elements.
The heart of this program consists of the three statements
Document document = parser.parse(new File(args[0]));
NodeList links = document.getElementsByTagName("link");
System.out.println("Input document has " +links.getLength() +" 'link' elements.");

// JAXP classes
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
// DOM classes
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
// JDK classes
import java.io.File;
/** Count the number of link elements in an RSS 0.91 document */
class DOMCountLinks {
/** Main program does it all */
static public void main(String args[]) {
try {
// JAXP-style initialization of DocumentBuilder
// (XML parser that builds DOM from document)
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder parser = docBuilderFactory.newDocumentBuilder();
// Parse XML document from file given by first argument
// into a DOM Document object
Document document = parser.parse(new File(args[0]));
// Process the Document object using the Java API version of
// the W3C DOM
NodeList links = document.getElementsByTagName("link");
System.out.println("Input document has " +
links.getLength() +
" 'link' elements.");
}
catch (Exception e) {
e.printStackTrace();
}
return;
}
}
FIGURE 7.7 DOM-based program for displaying the number of links in an RSS 0.91 document

The first of these statements opens the file specified by the first command-line argument and parses
the XML document contained in this file, producing a Document object that is the Java counterpart
to window.document in JavaScript. The second statement calls on the getElementsByTagName()
method (described in Table 5.5) to retrieve a list of Node objects corresponding to elements of type
link in the XML document. Finally, outputting the number of objects in this list completes the
program’s task.

4. Describe in detail about the XML schema, built in and user defined data type detail.
(13)
Any time XML is going to be used to communicate data between software applications. To
address such issues like limits on the number of digits the string
can contain? Can scientific notation (such as 4.34e4) be used? Are negative values only
represented using standard mathematical notation (by a leading minus sign, as in -23.43), or
can an accounting format (such as (23.43)) be used?, the W3C has developed an XML
vocabulary known as XML Schema. A key contribution of XML Schema is its definition of a
collection of standard data types. Each data type definition includes a specification of the
range of values that can be represented by the data type (for example, integers ranging
from −32,768 to 32,767) and details on how to represent those values as strings

Built-in Data Types


The XML Schema definition of each built-in type provides two kinds of information:
the character strings that may be used to represent a value of the
given type,
and the set of values that may be represented by such strings.
XML Schema has a wide variety of data types in order to support various applications. First,
it has data types that correspond to all of Java’s primitive types. In fact, for each of Java’s
primitive types except char—that is, for boolean, byte, short, int, long, float, and double—
XML Schema defines a data type with the same name.

TABLE 9.1 JAX-RPC Mappings between Supported Java Classes and XML Schema built-in Data
Types
Java Class XML Schema Type
String string
java.math.BigDecimal decimal
java.math.BigInteger integer
java.util.Calendar dateTime
java.util.Date dateTime
java.xml.namespace.QName QName
java.net.URI anyURI

User Defined Simple Types


In addition to restricting built-in types, simple data types can be defined in several
other ways. First, the base type for a restriction can be any simple type, user-defined as
well as built-in. Second, a simple type can be formed by taking the union of two or more
existing simple types. As a rather odd example, if we wanted to create a data type oddType
with values that are either the strings in the memberType enumeration described earlier or
a phone number as defined by phoneNumType, we could use the XML Schema markup

<simpleType name="oddType">
<union memberTypes="memberType phoneNumType" />
</simpleType>

The value of memberTypes is a white-space-separated list of simple type names.


Finally, a data type whose values are white-space-separated lists such as the value
of memberTypes just given can be created using the XML Schema list element. For
example,

<simpleType name="intList">
<list itemType="int" />
</simpleType>

defines a data type with values that are white-space-separated lists of int values. This
provides a simple way to represent an array of values

User Defined Complex Types


Complex Type is the XML Schema element used to define a complex type, that is, a type
whose values are represented in an XML document using markup.
<types>
<schema
targetNamespace="http://tempuri.org/types"
xmlns:tns="http://tempuri.org/types"
xmlns:soap11-enc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns="http://www.w3.org/2001/XMLSchema">
<import
namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
<complexType name="ExchangeValues">
<sequence>
<element name="dollars" type="double"/>
<element name="euros" type="double"/>
<element name="yen" type="double"/>
</sequence>
</complexType>
</schema>
</types>
FIGURE 9.17 Second set of lines from the WSDL document generated by wscompile for the
currency converter web service.

For example, Figure 9.17 contains a complexType element defining an XML Schema user
defined complex type named ExchangeValues. An instance document containing an element
anExchangeValue conforming with this type definition might look like
<anExchangeValue xsi:type="ExchangeValues">
<dollars>1.0</dollars>
<euros>0.746826</euros>
<yen>102.56</yen>
</anExchangeValue>

Notice that a data value of a complex type will be represented in an XML document by
an element that (with certain exceptions, such as empty elements) has as its content other
elements specified as part of the type definition. In the example just given, the element of
type ExchangeValues contains three elements (dollars, euros, and yen) as content.
Although the syntax of complexType is different from that of the XML DTD ELEMENT tag,
their purposes are similar: to define an XML content specification.
In the case of complexType, the content is specified indirectly for elements belonging to the
defined complex data type, while in the case of ELEMENT the content is specified directly for
an element. The sequence element is the XML Schema analog of the sequence operator “,”
in an XML DTD content specification, so the markup
<complexType name="ExchangeValues">
<sequence>
<element name="dollars" type="double"/>
<element name="euros" type="double"/>
<element name="yen" type="double"/>
</sequence>
</complexType>

is roughly equivalent to the XML DTD markup

<!ELEMENT anExchangeValue (dollars, euros, yen)>

6. Describe in detail about the differences between DTD and XML schema for defining
XML document structures with appropriate examples. (13)
S. DTD XSD (XML Schema Definition)
NO.
1. DTD are the declarations that XSD describes the elements in a XML
define a document type for document.
SGML.
2. It doesn’t support namespace. It supports namespace.
3. It is comparatively harder than It is relatively simpler than DTD.
XSD.
4. It doesn’t support datatypes. It supports datatypes.
5. SGML syntax is used for DTD. XML is used for writing XSD.
6. It is not extensible in nature. It is extensible in nature.
7. It doesn’t give us much control on It gives us more control on structure of XML
structure of XML document. document.

DTD
The abstract syntax for each flavor of XHTML 1.0 is defined by a set of text files known
collectively as an XML document type definition (DTD). To introduce you to the basic
elements of a DTD, let’s begin with a simple example drawn from an XHTML DTD:

<!ELEMENT html (head, body)>


<!ATTLIST html
lang NMTOKEN #IMPLIED
xml:lang NMTOKEN #IMPLIED
dir (ltr|rtl) #IMPLIED
id ID #IMPLIED
xmlns CDATA #FIXED 'http://www.w3.org/1999/xhtml'>
<!ENTITY gt "&#62;">

The first of these lines is an example of an element type declaration. Element type
declarations are used to specify the set of all valid elements in the language defined by the
DTD.
This example shows the actual element type declaration for the XHTML 1.0 html element.
The information following the element type name is known as the content specification
for the element; it provides information about the valid content of the element type being
declared. This particular declaration says that, in XHTML 1.0 Strict, the html element
must have two children, a head element followed by a body element. We’ll describe content
specifications in detail in Section 2.10.1.
The second line begins a tag that represents an XML attribute list declaration. As
you might guess, this provides information about the valid attributes for an element, in this
case for the html element. The attribute list declaration shown is equivalent to the actual
XHTML 1.0 Strict declaration for html and says that this element type has five attributes:
lang, xml:lang, dir, id, and xmlns. It also provides information such as the valid set of
values for each attribute and default value information. More will be said about this in
Section 2.10.2.
The final line is an example of an XML entity declaration. Such a tag is essentially
a macro definition, associating the name gt (an entity) with the string &#62;. We have
already learned how to “call” such macros using entity references such as &gt;. Now we
can see more clearly how they are processed: the application reading a document
containing an entity reference simply replaces the reference with the string represented by
the entity, and then recursively processes this string. In this case, the string is a character
reference, and the recursive processing will replace this reference with an appropriate
encoding of the Unicode Standard value for the greater-than character.

XML SCHEMA
A schema is much like an XML DTD: it is used to define the elements and attributes of an
XML vocabulary
To address such issues like limits on the number of digits the string can contain? Can
scientific notation (such as 4.34e4) be used? Are negative values only
represented using standard mathematical notation (by a leading minus sign, as in -23.43), or
can an accounting format (such as (23.43)) be used?, the W3C has developed an XML
vocabulary known as XML Schema. A key contribution of XML Schema is its definition of a
collection of standard data types. Each data type definition includes a specification of the
range of values that can be represented by the data type (for example, integers ranging
from −32,768 to 32,767) and details on how to represent those values as strings

Let's have a look at this XML document called "shiporder.xml":

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

<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide your heart</title>
<quantity>1</quantity>
<price>9.90</price>
</item>
</shiporder>

The XML schema for the above XML document is given below

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


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

<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string" minOccurs="0
"/>
<xs:element name="quantity" type="xs:positiveInteger"
/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/
>
</xs:complexType>
</xs:element>

</xs:schema>
7. (i) Demonstrate the building blocks of DOM. (7)
<<<<<<<REFER ANSWER FOR UNIT3 PART B Q.NO 3) ii) >>>>>>>>>>>
(ii) Classify the types of DTD. (6)
<<<<<<<REFER ANSWER FOR UNIT3 PART B Q.NO 4) >>>>>>>>>>>

8. Summarize on the following


(i) DOM based Parsing. (7)
<<<<<<<REFER ANSWER FOR UNIT3 PART B Q.NO 3) ii) >>>>>>>>>>>

(ii) SAX based Parsing. (6)


In SAX based parsing, the parser interact with an application as it reads an XML document. This is the
approach taken by SAX (Simple API for XML). In the SAX view of XML processing, as an XML parser is
reading an XML document, certain events occur.
For example, reading an element start tag is an event, as is reading its end tag or reading text
contained within an element.
SAX allows an application to register event listeners with the XML parser, much as the DOM event
model allowed a JavaScript program to register event listeners with a browser. A SAX parser calls
these listeners as events occur and passes them information about the events. There is no formal
standard defining SAX, and in fact no one owns the SAX API (it is in the public domain).
Figure 7.8 and Figure 7.9 contain a SAX2 recoding of the link-counting program from Figure 7.7. As
with the earlier DOM-based program, the JAXP factory approach can be used to obtain the parser,
and once again the API implementation used is pluggable (see [SUN-JAXP-1.2] for details). There is
one more step in this factory code than in the DOM example: a factory is used to obtain a SAXParser
(via a call to the newSAXParser() method), which in turn is used to obtain the actual XMLReader
parser. This extra step is not absolutely necessary, since a SAXParser instance can be used directly as
a parser (it provides a syntax similar to that of the DocumentBuilder DOM parser class). However,
SAXParser is a wrapper class specified by JAXP over top of the XMLReader class specified by the SAX2
API [SAX-2.0.1]. So, for portability purposes, it is probably advisable to use XMLReader rather than
SAXParser
// JAXP classes
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
// SAX classes
import org.xml.sax.XMLReader;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/** Count the number of link elements in an XML document */
class SAXCountLinks {
/** Source for RSS feed */
static String FEED_URL = "http://today.java.net/rss/21.rss";
/** Initialize XMLReader and set up event handlers */
static public void main(String args[]) {
try {
// JAXP-style initialization of SAX parser
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
XMLReader parser = saxFactory.newSAXParser().getXMLReader();
// SAX-style processing of RSS document at FEED_URL
parser.setContentHandler(new CountElementsHelper());
parser.parse(FEED_URL);
}
catch (Exception e) {
e.printStackTrace();
}
return;
}
FIGURE 7.8 Initial portion of SAX-based program for displaying the number of links in an
RSS 0.91 document.

/** Helper class containing SAX event handler methods */


private static class CountElementsHelper extends DefaultHandler {
/** Number of 'p' elements seen so far */
int numElements;
/** Constructor (allows for superclass initialization) */
CountElementsHelper() {
super();
}
/** Perform initialization for this instance */
public void startDocument() throws SAXException {
numElements = 0;
return;
}
/** Process the start of an element */
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts)
throws SAXException
{
if (qName.equals("link")) {
numElements++;
}
return;
}
/** Done with document; output final count */
public void endDocument() throws SAXException {
System.out.println("Input document has " +
numElements +
" 'link' elements.");
return;
}
}
}
FIGURE 7.9 Helper class portion of SAX-based program for displaying the number of links
in an RSS 0.91 document.
9. Write short notes on:
i) XPATH.(5)
<<<<<<<REFER ANSWER FOR UNIT3 PART B Q.NO 2) ii) >>>>>>>>>>>

ii) XSL elements.(4)


<<<<<<<REFER ANSWER FOR UNIT3 PART B Q.NO 3) ii) >>>>>>>>>>>

iii) Parse tree (4)


An internal element tree (an abstract syntax tree or parse tree) representing the
document, such as the tree given below is called a parse tree.

An Example XML Document


The image above represents books in this XML:

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


<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

10. Discover XML document to store voter ID, voter name, address and date of birth
details and validate the document with the help of DTD. (13)
Type the following in notepad and save it as vote.dtd
<? xml version = "1.0" encoding = "UTF-8">
<! DOCTYPE Voter_Information
[ <! Element Voter_information (Id, Name, Address, Date_of_birth)>
<! Element Id (#PCDATA)>
<! Element Name (#PCDATA)>
<! Element Address (#PCDATA)>
<! Element Date_of_birth (#PCDATA)>
]>

Type the following in notepad and save it as vote.xml in the same directory where vote.dtd
is stored
<?xml version="1.0"?>
<!DOCTYPE Voter_Information SYSTEM "vote.dtd">
<Voter_Information>
<Id> Voter Id = FGK99567 </Id>
<Name> Voter Name = Mohan Kumar </Name>
<Address> Address = Assam </Address>
<Date_of_birth> Date of birth = 05-03-1991 </Date_of_birth>
</Voter_Information>

Open the vote.xml file in browser.

OUTPUT
This XML file does not appear to have any style information associated with it.
The document tree is shown below.
<Voter_Information>
<Id> Voter Id = FGK99567 </Id>
<Name> Voter Name = Mohan Kumar </Name>
<Address> Address = Assam </Address>
<Date_of_birth> Date of birth = 05-03-1991 </Date_of_birth>
</Voter_Information>

Thus the document follows the rules mentioned in the DTD and it is displayed in browser.

11. (i) Explain XPATH nodes in detail. (7)


The root of the XPath parse tree is known as the document root. Like an instance
of Document in the DOM, this node of the XPath parse tree has a child node representing
the root of the element hierarchy in the parsed document; this node is called the document
element.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:template match="/">
<html>
<head>
<title>
HelloWorld.xsl (transformed)
</title>
</head>
<body>
<p><xsl:value-of select="child::message" /></p>
</body>
</html>
</xsl:template>
</xsl:transform>
FIGURE 7.12 An example XSL document HelloWorld.xsl

we have already seen some simple examples of XPath expressions in Figure 7.12. For
example, in the markup
<xsl:template match="/">
the value of the match attribute (/) is an XPath expression. This particular XPath expression
represents the XPath document root. An XPath expression such as this that represents one
or more nodes within an XPath parse tree is known as a location path. As another example,
in the markup
<xsl:value-of select="child::message" />
the value of the select attribute (child::message) is a location path. Unlike the / location
path, we cannot say which nodes are represented by this second location path without
knowing some additional information. In particular, this location path is defined relative to
some XPath parse tree node known as the context node for the location path.

In this second example, the location path consists of a single location step. More
generally, a location path can consist of multiple location steps separated by slash (/)
characters; we’ll see examples of such location paths later. Each location step consists of at
least two parts: an axis name followed by two colons (::) and a node test. In this example, child is the
axis name and message is the node test
TABLE 7.2 Some XPath 1.0 Axis Names
Name Relationship with Context Node

self The context node itself


child Any immediate descendant
descendant Any proper descendant
descendant-or-self Any descendant, including the context node itself

parent Immediate ancestor


ancestor Any proper ancestor, including the document root
(unless the context node is the document root)
ancestor-or-self Any ancestor, including the context node itself

preceding-sibling Any sibling of the context node that precedes the


context node in the document
following-sibling Any sibling of the context node that follows the
context node in the document
attribute Any attribute defined for the context node

(ii) Explain about XML Schema in detail.(6)


<<<<<<<REFER ANSWER FOR UNIT3 PART B Q.NO 4) >>>>>>>>>>>

12. Explain in detail about


(i) XSL and XSLT transformation(7)
XSL
<<<<<<<REFER ANSWER FOR UNIT3 PART B Q.NO 3) i ) >>>>>>>>>>>
XSLT transformation
XSLT is used for general-purpose transformation from one XML application to another, the
default namespace for the XSLT document is normally set to that of the target application.
In this example, since the goal is to generate an XHTML document, the XHTML namespace
is specified as the default namespace for the XSLT document.
The content of the root element often consists of one or more template elements; there is
just one such element in the example. Each template represents a template rule, which
typically consists of two parts: an XPath expression specified as the value of the template
element’s match attribute and known as the template rule’s pattern; and the content of the
template rule, which is known as the template portion of the rule.
Software for performing an XSLT transformation, such as JAXP, is known as an XSLT
processor. Recall that an XSLT processor is given two inputs—an XSLT document and a
source XML document—and produces a single result XML document. Internally, an XSLT
processor represents each of these documents as an XPath tree, called the source tree, the
style-sheet tree, and the result tree, respectively. Since all three trees are XPath trees,
nodes in any of these trees (or more generally, lists of nodes) can be referenced using XPath
expressions
The template contains a single XSLT element of type value-of. This type of XSLT element
causes a text node to be added to the result tree. The content of this text node is formed by
first evaluating the XPath expression that is the value of the select attribute (child::message
in our example), producing a node list. The XPath context node used in this evaluation is the
node that was matched by the template rule whose template is being instantiated (the
document root node in our example). Given that the input for our XSLT example is the XML
document of Figure 7.13, the XPath expression child::message evaluates to a node list
containing a single document element node of type message.

Next, after the node list has been produced, the XSLT processor in effect calls the XPath
string() function on the node list. That is, all of the text in the first node (“first” here
meaning the first in the order of document appearance) and in its descendants is
concatenated (in order of document appearance) into a single string. This string becomes
the content of the text node added to the result tree. So, in our example, a text node
containing Hello World! Is added to the result tree. Because the value-of element was a
child of a p element in the style-sheet tree, the text node generated will be a child of the
corresponding p element in the result tree, as shown in Figure 7.16.

(ii) Comparison of DOM & SAX(6)

S.No. SAX DOM


1 It is called a Simple API for XML Parsing. It is called as Document Object Model.
2 It’s an event-based parser. It stays in a tree structure.
3 SAX Parser is slower than DOM Parser. DOM Parser is faster than SAX Parser.
4 Best for the larger sizes of files. Best for the smaller size of files.
5 It is suitable for making XML files in Java. It is not good at making XML files in low
memory.
6 The internal structure can not be created by The internal structure can be created by
SAX Parser. DOM Parser.
7 It is read-only. It can insert or delete nodes.
8 In the SAX parser backward navigation is not In DOM parser backward and forward
possible. search is possible
9 Suitable for efficient memory. Suitable for large XML document.
10 A small part of the XML file is only loaded in It loads whole XML documents in memory.
memory.

13. (i) List out data types data types of XML (7)

XML Schema has a lot of built-in data types. The most common types are:

 String, boolean, byte, short, int, long, float, and double

(ii) Explain about the attributes of XML. (6)


An XML vocabulary is created by specifying a complete description of the elements and
attributes for a specific type of XML document.
XML elements can have attributes, just like HTML.
Attributes are designed to contain data related to a specific element.
XML Attributes Must be Quoted
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'>
or you can use character entities:
<gangster name="George &quot;Shotgun&quot; Ziegler">

XML Attributes for Metadata


Sometimes ID references are assigned to elements. These IDs can be used to identify XML
elements in much the same way as the id attribute in HTML. This example demonstrates
this:

<messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>
The id attributes above are for identifying the different notes. It is not a part of the note
itself.

Metadata (data about data) should be stored as attributes, and the data itself should be
stored as elements.

14. Summarize in detail the XML schema, built in and user defined data types. (13)
<<<<<<<REFER ANSWER FOR UNIT3 PART B Q.NO 4) >>>>>>>>>>>

15. Demonstrate how can both Internal and External DTDs be used in an XML File?
Show with an Example (13)

In fact, you can use both internal and external DTDs at the same time by using these forms
of the
<!DOCTYPE> element: <!DOCTYPE rootname SYSTEM URL [ DTD ]> for private external
DTDs,
and <!DOCTYPE rootname PUBLIC FPI URL [ DTD ]> for public external DTDs.

In this case, the external DTD is specified by URL and the internal one by DTD .

Here's an example in which I've removed the <PRODUCT> element from the external DTD
ch03_10.dtd:

<!ELEMENT DOCUMENT (CUSTOMER)*>


<!ELEMENT CUSTOMER (NAME,DATE,ORDERS)>
<!ELEMENT NAME (LAST_NAME,FIRST_NAME)>
<!ELEMENT LAST_NAME (#PCDATA)>
<!ELEMENT FIRST_NAME (#PCDATA)>
<!ELEMENT DATE (#PCDATA)>
<!ELEMENT ORDERS (ITEM)*>
<!ELEMENT ITEM (PRODUCT,NUMBER,PRICE)>
<!ELEMENT NUMBER (#PCDATA)>
<!ELEMENT PRICE (#PCDATA)>

Now I'll specify that I want to use this external DTD in the document's <!DOCTYPE> element
and then also add square brackets, [ and ] , to enclose an internal DTD:

<?xml version = "1.0" standalone="no"?> <!DOCTYPE DOCUMENT SYSTEM "ch03_10.dtd" [


. . . ]>
<DOCUMENT>
<CUSTOMER>
<NAME> <LAST_NAME>Smith</LAST_NAME>
<FIRST_NAME>Sam</FIRST_NAME>
</NAME>
<DATE>October 15, 2003</DATE>
<ORDERS>
<ITEM>
<PRODUCT>
<PRODUCT_ID> 198348209 </PRODUCT_ID>
</PRODUCT>
<NUMBER>8</NUMBER>
<PRICE>.25</PRICE>
</ITEM>
.
.
.
<ITEM>
<PRODUCT>
<PRODUCT_ID> 198348206 </PRODUCT_ID>
</PRODUCT>
<NUMBER>6</NUMBER>
<PRICE>.50</PRICE>
</ITEM>
</ORDERS>
</CUSTOMER>
</DOCUMENT>

Next, I add the declaration of the <PRODUCT> element to the internal part of the DTD, like
this:

<?xml version = "1.0" standalone="no"?>


<!DOCTYPE DOCUMENT SYSTEM "ch03_10.dtd" [ <!ELEMENT PRODUCT (PRODUCT_ID)>
<!ELEMENT PRODUCT_ID (#PCDATA)> ]>
<DOCUMENT>
<CUSTOMER>
<NAME>
<LAST_NAME>Smith</LAST_NAME>
<FIRST_NAME>Sam</FIRST_NAME>
</NAME>
<DATE>October 15, 2003</DATE>
<ORDERS>
<ITEM>
<PRODUCT>
<PRODUCT_ID> 198348209 </PRODUCT_ID>

</PRODUCT>
<NUMBER>8</NUMBER>
<PRICE>.25</PRICE>
</ITEM>
.
.
.
<ITEM>
<PRODUCT>
<PRODUCT_ID> 198348206 </PRODUCT_ID>
</PRODUCT>
<NUMBER>6</NUMBER>
<PRICE>.50</PRICE>
</ITEM>
</ORDERS>
</CUSTOMER>
</DOCUMENT>
And that's all it takes; now this DTD uses both internal and external parts .

If It's Both Internal and External, Which Takes Precedence?


Theoretically, if an element or attribute is defined in both an internal and external DTD, the
definition in the internal DTD is supposed to take precedence, overwriting the external
definition. Things were arranged that way to let you customize external DTDs as you like.
However, my experience is that most XML processors simply consider it an error if there is
an element or attribute conflict between internal and external DTDs, and they usually just
halt.

16. Explain the procedure for validating the XML Documents. (13)
Validation is a process by which an XML document is validated. An XML
document is said to be valid if its contents match with the elements,
attributes and associated document type declaration(DTD), and if the
document complies with the constraints expressed in it. Validation is dealt
in two ways by the XML parser. They are −

 Well-formed XML document


 Valid XML document

Well-formed XML Document


An XML document is said to be well-formed if it adheres to the following
rules −
 Non DTD XML files must use the predefined character entities
for amp(&), apos(single quote), gt(>), lt(<), quot(double
quote).
 It must follow the ordering of the tag. i.e., the inner tag must
be closed before closing the outer tag.
 Each of its opening tags must have a closing tag or it must be
a self ending tag.(<title>....</title> or <title/>).
 It must have only one attribute in a start tag, which needs to
be quoted.
 amp(&), apos(single quote), gt(>), lt(<), quot(double
quote) entities other than these must be declared.
Example
Following is an example of a well-formed XML document −

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


<!DOCTYPE address
[
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>

<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

The above example is said to be well-formed as −


 It defines the type of document. Here, the document type
is element type.
 It includes a root element named as address.
 Each of the child elements among name, company and phone
is enclosed in its self explanatory tag.
 Order of the tags is maintained.

Valid XML Document


If an XML document is well-formed and has an associated Document Type
Declaration (DTD), then it is said to be a valid XML document.

17. Summarize about XML Schema with an example. (13)


<<<<<<<REFER ANSWER FOR UNIT3 PART B Q.NO 4) >>>>>>>>>>>

PART – C
1. Briefly Explain about MVC architecture in detail. (15)
Most real-world web applications are of course much larger and may contain a large
number of components (servlets and JSP documents) as well as numerous support files
(such as JavaBeans classes). While there are many possible ways of organizing the
components and support files for such an application, one approach, called the model-view-
controller paradigm, is widely used in one form or another in many web applications. In fact,
the MVC paradigm was elucidated long before the Web existed, and can be applied in any
system that has both data processing and data presentation requirements.
But our focus will be on its use with web applications.
A web application following the MVC organizational paradigm will typically have a single
controller that receives all incoming HTTP requests. Because the controller provides a single
point of entry to the application, application-wide tasks such as initialization, logging, and
controlling access to the application are often performed by the controller.
The controller may also interact with model components of the application. These (model
components) are software components that represent the persistent data of the application
and server-side processing performed on this data. Finally, when the controller and model
software have performed all necessary pre-processing of a request, the controller selects an
appropriate view(presentation) component and forwards the HTTP request to that
component. The view component will generally obtain data from the request and/or model
components and then generate an HTTP response that presents a formatted view of this
data.

In a web application written using JSP, the controller portion is often implemented as
one or more Java servlets. The model components will typically consist of JavaBeans
classes
and/or a database (or other storage mechanism). Each view component is normally a JSP
document. Each such JSP document might also access JavaBeans objects and tag libraries
to obtain model data for inclusion in the response it generates. Furthermore, portions of
the response might be generated by calling on other servlets or JSP documents within the
web application.

Advantages of MVC: Key Benefits


Here, are major benefits of using MVC architecture:

 Easy code maintenance which is easy to extend and grow


 MVC Model component can be tested separately from the user
 Easier support for new types of clients
 Development of the various components can be performed parallelly.
 It helps you to avoid complexity by dividing an application into the three
units. Model, view, and controller
 It only uses a Front Controller pattern which process web application
requests through a single controller.
 Offers the best support for test-driven development
 It works well for Web apps which are supported by large teams of web
designers and developers.
 Provides clean separation of concerns(SoC).
 Search Engine Optimization (SEO) Friendly.
 All classes and objects are independent of each other so that you can test
them separately.
 MVC design pattern allows logical grouping of related actions on a
controller together.

Disadvantages of using MVC


 Difficult to read, change, unit test, and reuse this model
 The framework navigation can some time complex as it introduces new
layers of abstraction which requires users to adapt to the decomposition
criteria of MVC.
 No formal validation support
 Increased complexity and Inefficiency of data
 The difficulty of using MVC with the modern user interface
 There is a need for multiple programmers to conduct parallel
programming.
 Knowledge of multiple technologies is required.
 Maintenance of lots of codes in Controller

3-tier Architecture vs. MVC Architecture


Parameter 3-Tier Architecture MVC Architecture
Communication This type of architecture pattern never All layers communicate directly using
communicates directly with the data triangle topology.
layer.
Usage 3-tier: widely used in web applications Generally used on applications that run on a
where the client, data tiers, and single graphical workstation.
middleware a run on physically
separate platforms.

2. Summarize about XML schema and XML Parsers and Validation. (15)
<<<<<<<REFER ANSWER FOR UNIT3 PART B
Q.No 6) for XML schema
Q.No 8) for XML Parsers
Q.No 16) for XML Validation >>>>>>>>>>>

3. Get the students’ details like name, register number and mark using form. Generate
DTD for this XML document. Name Reg no Mark. (15)
XYZ 1000 90
ABC 1001 80
RST 1002 89
PQR 1003 87
Generate the collected information in the descending order of marks using XSLT. Results
should be displayed in the above format. Write a source code and explain the same.

student.xml File
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl' href='cgpa.xsl'?>
<class>
<student>
<name> XYZ </name>
<regno> 1000 </regno>
<mark> 90</mark>
</student>
<student>
<name> ABC </name>
<regno> 1001 </regno>
<mark> 80</mark>
</student>
<student>
<name> RST </name>
<regno> 1002</regno>
<mark> 89 </mark>
</student>
<student>
<name> PQR </name>
<regno> 1002</regno >
<mark> 87 </mark>
</student>
</class>

cgpa.xsl File
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Student list in descending order of their CGPA.</h2>
<table border="1">
<tr bgcolor="lightblue">
<th>ID</th>
<th>Name</th>
<th>MARK</th>
</tr>
<xsl:for-each select="class/student">
<xsl:sort select="mark" order="descending" data-type="number"/>
<tr>
<td><xsl:value-of select="regno"/></td>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="mark"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

4. Explain how XSLT transforms the document from one (Word) type to other type
(HTML). (15)
<<<<<REFER ANSWER FOR UNIT3 PART B Q.No 12) >>>>>>>>>>>

5. Summarize the Advantages, Disadvantages and Features of SAX parser


Advantages of SAX

 Low memory needs since the XML file is never entirely in memory.

 It deals with the XML streams.

 Fast Operation speed.

 Use callback procedures to identify and respond only certain XML elements.

Read Also
Android SAX Parser

Disadvantages of SAX
 The file has to be parsed entirely to access any node. Thus, getting the 10 nodes included in

a catalog ended up in parsing 10 times the same file.

 Poor navigation abilities : There is no way to get easily the children of a given node or the

list of "B" nodes

 Document doesn't modified.

 SAX does not create an in-memory document structure

Features of SAX Parser


A SAX parser can be viewed as a mechanism for transforming an XML text document into
a stream of events corresponding to the markup and character data contained in the original
document

An alternative to the DOM approach is to have the parser interact with an application as it
reads an XML document. This is the approach taken by SAX (Simple API for XML). In
the SAX view of XML processing, as an XML parser is reading an XML document, certain
events occur. For example, reading an element start tag is an event, as is reading its end tag
or reading text contained within an element. SAX allows an application to register event
listeners with the XML parser, much as the DOM event model described in Section 5.6
allowed a JavaScript program to register event listeners with a browser. A SAX parser calls
these listeners as events occur and passes them information about the events.
There is no formal standard defining SAX, and in fact no one owns the SAX API
(it is in the public domain). However, SAX is, according to the official SAX Web site
(http://www.saxproject.org/), “the first widely adopted API for XML in Java, and is a
‘de facto’ standard.” The version described here is SAX 2.0.1, often referred to as SAX2
[SAX-2.0.1].
Figure 7.8 and Figure 7.9 contain a SAX2 recoding of the link-counting program
from Figure 7.7.
Once the parser has been obtained, a two-step process is followed to input an XML
document. First, the parser is passed—via a call to its setContentHandler() method—an
instance of a Java class that defines the event-handling methods to be called by the parser;
more on this class shortly. Second, the parse() method of the parser is called with an
argument representing the URL of the XML document to be parsed.
// JAXP classes
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
// SAX classes
import org.xml.sax.XMLReader;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/** Count the number of link elements in an XML document */
class SAXCountLinks {
/** Source for RSS feed */
static String FEED_URL = "http://today.java.net/rss/21.rss";
/** Initialize XMLReader and set up event handlers */
static public void main(String args[]) {
try {
// JAXP-style initialization of SAX parser
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
XMLReader parser = saxFactory.newSAXParser().getXMLReader();
// SAX-style processing of RSS document at FEED_URL
parser.setContentHandler(new CountElementsHelper());
parser.parse(FEED_URL);
}
catch (Exception e) {
e.printStackTrace();
}
return;
}
FIGURE 7.8 Initial portion of SAX-based program for displaying the number of links in an
RSS 0.91 document.

/** Helper class containing SAX event handler methods */


private static class CountElementsHelper extends DefaultHandler {
/** Number of 'p' elements seen so far */
int numElements;
/** Constructor (allows for superclass initialization) */
CountElementsHelper() {
super();
}
/** Perform initialization for this instance */
public void startDocument() throws SAXException {
numElements = 0;
return;
}
/** Process the start of an element */
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts)
throws SAXException
{
if (qName.equals("link")) {
numElements++;
}
return;
}
/** Done with document; output final count */
public void endDocument() throws SAXException {
System.out.println("Input document has " +
numElements +
" 'link' elements.");
return;
}
}
}
FIGURE 7.9 Helper class portion of SAX-based program for displaying the number of links
in an RSS 0.91 document.

You might also like