Web Technology UNIT IV
Web Technology UNIT IV
Lecture Plan
UNIT IV
/
nr
file, there can only be one root element. The root element must encapsulate all other
o.
elements--meaning, these other elements must show up after the opening root tag and before
e.c
the closing root tag. Here is an example of an XML document with the root element
ub
"phonebook".
et
cs
XML Code:
://
<phonebook> <number> </number> <name> </name> </phonebook> Notice how the root
tp
element "phonebook" surrounds the other elements in XML file. Below is a broken XML
ht
file. Try to see if you can find what is wrong with this file before reading the caption below.
XML Code:
<phonebook> <number> </number> <name> </phonebook> </name> You should have
noticed that the root element "phonebook" did not contain all other elements because the
closing name tag </name> is not between the root element tags <phonebook> and
</phonebook>. Another rule for XML files is that only one root element per file is allowed.
Our previous example followed this rule, but our example below does not because it has two
root elements. What are the two root elements?
XML Code:
<phonebook> <number> </number> <name> </name> </phonebook> <diary> <date>
</date> </diary> If you said the two root elements were "phonebook" and "diary", then you
got it right! Phone book is the first element to appear in this file, so it is automatically a root
element.After the phonebook element is closed, no other elements should follow because
http://csetube.co.nr/
GKMCET
Lecture Plan
XML can only have one root element per file. Because the "diary" element did not follow this
rule, it transformed this XML file into a lawless, rule-breaking file! XML CDATA All text
in an XML document will be parsed by the parser.But text inside a CDATA section will be
ignored by the parser.
PCDATA - Parsed Character Data
XML parsers normally parse all the text in an XML document.When an XML element is
parsed, the text between the XML tags is also parsed: <message>This text is also
parsed</message> The parser does this because XML elements can contain other elements,
as in this example, where the <name> element contains two other elements (first and last):
/
nr
<name><first>Bill</first><last>Gates</last></name> and the parser will break it up into
o.
e.c
sub-elements like this: <name> <first>Bill</first> <last>Gates</last> </name> Parsed
ub
Character Data (PCDATA) is a term used about text data that will be parsed by the XML
et
parser.
cs
The term CDATA is used about text data that should not be parsed by the XML parser.
ht
Characters like "<" and "&" are illegal in XML elements. "<" will generate an error because
the parser interprets it as the start of a new element. "&" will generate an error because the
parser interprets it as the start of an character entity.Some text, like JavaScript code, contains
a lot of "<" or "&" characters. To avoid errors script code can be defined as
CDATA.Everything inside a CDATA section is ignored by the parser. A CDATA section
starts with "<![CDATA[" and ends with "]]>": <script> <![CDATA[ function matchwo(a,b)
{ if (a < b && a < 0) then { return 1; } else { return 0; } } ]]> </script> In the example above,
everything inside the CDATA section is ignored by the parser. XML Parsers Here's how a
simple XML file would look like. Notice how all the Tags are Closed. This is called Well
Formed ness. All the Tags in the XML file needs to be closed. Else the parser would throw an
Exception while parsing this XML file.
<?xml version='1.0' encoding='us-ascii'?> <!DOCTYPE Library> <Library> <!-- Book 1
Comments --> <Book ISBN="8763-343-2343" > <Title>Professional JINI</Title>
<Author>Sing Li</Author> <Publisher>Wrox Publications</Publisher>
http://csetube.co.nr/
GKMCET
Lecture Plan
/
nr
2. Also in the XML File we have added comments for Book1 using the Following syntax <!--
o.
e.c
Book 1 Comments -->
ub
The Element called "Book" has both Attributes and More Tags under it. For Example in
et
the above XML file, for the Book Element, ISBN is attribute and Title, Author and
cs
Publisher are sub Tags under the Book Element. If the Tags and Elements need to be added
://
tp
compulsorily or not in the XML file along with the Element is defined by DTD (Document
ht
Type Definition) file. For Example in the above XML file, For Book Element, ISBN might
be compulsory if the search Based on ISBN is supported. And Date Published Tag may not
be necessary at all times if there's no search facility based on get the Most Recent Books. We
will explaining how to create DTD's after next few sections.
Notice how we declared a Empty Tag for <Date_Published/>, under Second Book. This
Statement is equivalent to writing <Date_Published><Date_Published/>. This Feature
Could save your XML File Size if there is no Data required between the Tags.
From this point we will be explaining how to use different Kinds of Parsers that are available
for processing the XML files and how to use them. XML file is just plain Text
http://csetube.co.nr/
GKMCET
Lecture Plan
File. Now the next step is to retrieve the data provided in this XML file. In this Tutorial we
will be explaining how to use the Javasoft's XML parser. JavaSoft currently provides three
parsers. They are
SAX (Simple API for XML) Parser
DOM (Document Object Model) Parser and
XSLT (XML Style Sheet) Parsers.
In the Next Section, we will be developing code to retrieve the text provided in the XML tags
using these Parsers.
/
nr
XML DTD
o.
e.c
The purpose of a DTD is to define the structure of an XML document. It defines the structure
ub
http://csetube.co.nr/
GKMCET
Lecture Plan
ELEMENTS AND ATTRIBUTES : Each Tag in a XML file can have Element and
Attributes. Here's how a Typical Tag looks like, <Email to="[email protected]"
from="[email protected]" subject="Introducing XML"> </Email> In this Example, Email
is called as Element. This Element called E-mail has three attributes, to, from and subject.
The Following Rules need to be followed while declaring the XML Elements Names:
Names can contain letters, numbers, and other characters
Names must not start with a number or "_" (underscore)
Names must not start with the letters xml (or XML or Xml ..)
Names can not contain spaces
/
nr
o.
e.c
Any name can be used, no words are reserved, but the idea is to make names descriptive.
ub
Avoid "-" and "." in names. It could be a mess if your software tried to subtract name from
cs
first (author-name) or think that "name" is a property of the object "author" (author.name).
://
tp
Empty Tags :
ht
In cases where you don't have to provide any sub tags, you can close the Tag, by providing a
"/" to the Closing Tag. For example declaring <Text></Text> is same a declaring <Text />
Comments in XML File : Comments in XML file are declared the same way as Comments
in HTML File.
<Text>Welcome To XML Tutorial </Text> <!-- This is a comment --> <Subject />
The XML Prolog XML file always starts with a Prolog. The minimal prolog contains a
declaration that identifies the document as an XML document, like this: <?xml
version="1.0"?> The declaration may also contain additional information, like this: <?xml
version="1.0" encoding="ISO-8859-1" standalone="yes"?> The XML declaration may
contain the following attributes: version Identifies the version of the XML markup language
used in the data. This attribute is not optional. encoding
Identifies the character set used to encode the data. "ISO-8859-1" is "Latin-1" the Western
European and English language character set. (The default is compressed Unicode: UTF-8.).
For a List of all supported Encoding Types in JDK 1.2 please Encodings Supported in JDK
http://csetube.co.nr/
GKMCET
Lecture Plan
standalone Tells whether or not this document references an external entity or an external
data type specification (see below). If there are no external references, then "yes" is
appropriate Processing Instructions An XML file can also contain processing instructions
that give commands or information to an application that is processing the XML data.
Processing instructions have the following format: <?target instructions?> where the target is
the name of the application that is expected to do the processing, and instructions is a string
of characters that embodies the information or commands for the application to process. 4.3
XML NAMESPACES XML Namespaces provide a method to avoid element name
/
conflicts.
nr
Name Conflicts
o.
e.c
In XML, element names are defined by the developer. This often results in a conflict when
ub
trying to mix XML documents from different XML applications. This XML carries HTML
et
XML carries information about a table (a piece of furniture): <table> <name>African Coffee
tp
were added together, there would be a name conflict. Both contain a <table> element, but the
elements have different content and meaning.An XML parser will not know how to handle
these differences.
Solving the Name Conflict Using a Prefix
Name conflicts in XML can easily be avoided using a name prefix.This XML carries
information about an HTML table, and a piece of furniture: <h:table> <h:tr>
<h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table> <f:name>African
Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table>
In the example above, there will be no conflict because the two <table> elements have
different names.
XML Namespaces - The xmlns Attribute
When using prefixes in XML, a so-called namespace for the prefix must be defined.
The namespace is defined by the xmlns attribute in the start tag of an element. The
namespace declaration has the following syntax. xmlns:prefix="URI". <root> <h:table
http://csetube.co.nr/
GKMCET
Lecture Plan
/
nr
xmlns:f="http://www.w3schools.com/furniture"> <h:table> <h:tr> <h:td>Apples</h:td>
o.
e.c
<h:td>Bananas</h:td> </h:tr> </h:table> <f:table> <f:name>African Coffee Table</f:name>
ub
<f:width>80</f:width> <f:length>120</f:length>
et
cs
://
tp
ht
http://csetube.co.nr/
GKMCET
Lecture Plan
/
nr
<td>Apples</td> <td>Bananas</td> </tr> </table> This XML carries information about a
o.
e.c
piece of furniture: <table xmlns="http://www.w3schools.com/furniture"> <name>African
ub
What is RSS?
cs
Really Simple Syndication (RSS) is a lightweight XML format designed for sharing
://
tp
headlines and other Web content. Think of it as a distributable "What's New" for your site.
ht
Originated by UserLand in 1997 and subsequently used by Netscape to fill channels for
Netcenter, RSS has evolved into a popular means of sharing content between sites (including
the BBC, CNET, CNN, Disney, Forbes, Motley Fool, Wired, Red Herring, Salon, Slashdot,
ZDNet, and more). RSS solves myriad problems webmasters commonly face, such as
increasing traffic, and gathering and distributing news. RSS can also be the basis for
additional content distribution services.
http://csetube.co.nr/
GKMCET
Lecture Plan
RSS Syntax
RSS defines an XML grammar (a set of HTML-like tags) for sharing news. Each
RSS text file contains both static information about your site, plus dynamic information about
your new stories, all surrounded by matching start and end tags. Each story is defined by an
<item> tag, which contains a headline TITLE, URL, and DESCRIPTION. Here's an
example: ... <item> <title>RSS Resources</title>
<link>http://www.webreference.com/authoring/languages/xml/rss/</link>
<description>Defined in XML, the Rich Site Summary (RSS) format has quietly become a
dominant format for distributing headlines on the Web. Our list of links gives you the tools,
/
nr
tips and tutorials you need to get started using RSS. 0323</description> </item> ... Each RSS
o.
e.c
channel can contain up to 15 items and is easily parsed using Perl or other open source
ub
software.
et
The real trick of Ajax is updating a segment of the page without actually having to reload the
://
tp
entire page. This little trick is often done by utilizing a Javascript property known as
ht
innerHTML. Each HTML element on a page has an innerHTML associated with it that can be
changed at any time. For us, we need to update it when our ajax-example.php script has
finished executing. Updating the order.html Page First we need to create a new div on this
page that will contain the results of the query. After we have that in place we can update the
div's innerHTML with the information returned by ajax-example.php. Remember that this
result is stored inside ajaxRequest.responseText.
order.html HTML/Javascript Code:
<html> <body> <script language="javascript" type="text/javascript"> <!-- //Browser Support
Code function ajaxFunction(){ var ajaxRequest; // The variable that makes Ajax possible!
try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ //
Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ //
Something went wrong alert("Your browser broke!"); return false; } } } // Create a function
that will receive data sent from the server ajaxRequest.onreadystatechange = function(){
http://csetube.co.nr/
GKMCET
Lecture Plan
/
nr
id='ajaxDiv'>Your result will display here</div> </body> </html> Quick Ajax Recap
o.
e.c
So far we have created a new MySQL table, written a new PHP script and updated order.html
ub
twice. If you have followed the directions in the Ajax MySQL lesson and created the MySQL
et
table ajax_example and ajax-example.php script then the updated order.html page will
cs
Display:
ht
http://csetube.co.nr/
GKMCET
Lecture Plan
/
nr
o.
e.c
ub
et
cs
://
tp
ht
http://csetube.co.nr/
GKMCET
Lecture Plan
/
nr
} txt=txt + "</tr>"; } txt=txt + "</table>";
o.
e.c
document.getElementById('txtCDInfo').innerHTML=txt; } } xmlhttp.open("GET",url,true);
ub
xmlhttp.send(); }
et
cs
://
tp
ht
http://csetube.co.nr/
GKMCET
Lecture Plan
/
nr
text value of the first <title> element:
o.
e.c
Example
ub
txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
et
The following example retrieves the text value of the "lang" attribute of the first <title>
://
tp
element:
ht
Example
Txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");
Change the Value of an Element
The following example changes the text value of the first <title> element:
Example
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0]; x.nodeValue="Easy
Cooking";
Create a New Attribute
The XML DOM setAttribute() method can be used to change the value of an existing
attribute, or to create a new attribute.The following example adds a new attribute
(edition="first") to each <book> element: Example:
x=xmlDoc.getElementsByTagName("book"); for(i=0;i<x.length;i++)
http://csetube.co.nr/
GKMCET
Lecture Plan
{ x[i].setAttribute("edition","first"); }
Create an Element
o The XML DOM createElement() method creates a new element node.
o The XML DOM createTextNode() method creates a new text node.
o The XML DOM appendChild() method adds a child node to a node (after the last child).
To create a new element with text content, it is necessary to both create a new element node
and a new text node, and then append it to an existing node.The following example creates a
/
new element (<edition>), with the following text: First, and adds it to the first <book>
nr
element: Example:
o.
newel=xmlDoc.createElement("edition");
e.c
newtext=xmlDoc.createTextNode("First"); newel.appendChild(newtext);
ub
Remove an Element
The following example removes the first node in the first <book> element:
Example
x=xmlDoc.getElementsByTagName("book")[0]; x.removeChild(x.childNodes[0]);
http://csetube.co.nr/
GKMCET
Lecture Plan
4.6 EVENT_ORIENTED PARSING :SAX Getting the SAX Classes and Interfaces Once
you have your parser, you need to locate the SAX classes. These classes are almost always
included with a parser when downloaded, and Xerces is no exception. If this is the case with
your parser, you should be sure not to download the SAX classes explicitly, as your parser is
probably packaged with the latest version of SAX that is supported by the parser.. To prevent
errors, we need to remove the references within the XML document to an external DTD,
which constrains the XML, and the XSL stylesheets that transform it. You should comment
out these two lines in the XML document, as well as the processing instruction to Cocoon
requesting XSL transformation: <?xml version="1.0"?> <!-- We don't need these yet
/
nr
<?xml-stylesheet href="XSL\JavaXML.html.xsl" type="text/xsl"?> <?xml-stylesheet
o.
e.c
href="XSL\JavaXML.wml.xsl" type="text/xsl" media="wap"?> <?cocoon-process
ub
commented, note the full path to the XML document. In the next chapter, we will look at how
ht
to resolve this reference for the XML document. </JavaXML:Contents> <!-- Leave out until
DTD Section <JavaXML:Copyright>&OReillyCopyright;</JavaXML:Copyright> -->
</JavaXML:Book> SAX Readers Without spending any further time on the preliminaries,
lets begin to code. Our first program will be able to take an XML file as a command-line
parameter, and parse that file. We will build document callbacks into the parsing process so
that we can display events in the parsing process as they occur, which will give us a better
idea of what exactly is going on under the hood.If you are not sure whether you have the
SAX classes, look at the jar file or class structure used by your parser. The SAX classes are
packaged in the org.xml.sax structure. The latest version of these includes 17 classes in this
root directory, as well as 9 classes in org.xml.sax.helpers and 2 in org.xml.sax.ext. If you are
missing any of these classes, you should try to contact your parsers vendor to see why the
classes were not included with your distribution. It is possible that some classes may have
been left out if they are not supported in whole.*
http://csetube.co.nr/
GKMCET
Lecture Plan
These class counts are for SAX 2.0 as well; fewer classes may appear if only SAX 1.0 is
supported. The first thing we need to do is get an instance of a class that conforms to the
SAX org.xml.sax.XMLReader interface. Instantiating a Reader SAX provides an interface
that all SAX-compliant XML parsers should implement. This allows SAX to know exactly
what methods are available for callback and use within an application. For example, the
Xerces main SAX parser class, org. apache.xerces.parsers.SAXParser, implements the
org.xml.sax.XMLReader interface. If you have access to the source of your parser, you
should see the same interface implemented in your parsers main SAX parser class. Each
/
XML parser must have one class (sometimes more!) that implements this interface, and that
nr
o.
is the class we need to instantiate to allow us to parse XML: XMLReader parser = new
e.c
SAXParser(); // Do something with the parser parser.parse(uri); For those of you new to SAX
ub
entirely, it may be a bit confusing not to see the instance variable we used named reader or
et
XMLReader. While that would be a normal convention, the SAX 1.0 classes defined the
cs
://
main parsing interface as Parser, and a lot of legacy code has variables named parser because
tp
http://csetube.co.nr/
GKMCET
Lecture Plan
// Instantiate a parser XMLReader parser = new SAXParser(); } /** * <p> * This provides a
command-line entry point for this demo. * </p> */ public static void main(String[] args) { if
(args.length != 1) { System.out.println("Usage: java SAXParserDemo [XML URI]");
System.exit(0); } String uri = args[0]; SAXParserDemo parserDemo = new
SAXParserDemo(); parserDemo.performDemo(uri); } } You should be able to load and
compile this program if you made the preparations talked about earlier to ensure the SAX
classes are in your class path. This simple program doesnt do much yet; in fact, if you run it
and supply a bogus filename or URI as an argument, it should happily grind away and do
/
nothing, other than print out the initial Parsing XML file message. Thats because we
nr
have only instantiated a parser, not requested that our XML document be parsed. Parsing the
o.
e.c
Document Once a parser is loaded and ready for use, we can instruct it to parse our
ub
and this method can accept either an org.xml.sax.InputSource,or a simple string URI. For
cs
://
now, we will defer talking about using an InputSource and look at passing in a simple URI.
tp
Although this URI could be a network-accessible address, we will use the full path to the
ht
XML document we prepared for this use earlier. If you did choose to use a URL for network-
accessible XML documents, you should be aware that the application would have to resolve
the URL before passing it to the parser (generally this requires only some form of network
connectivity). We need to add the parse() method to our program, as well as two exception
handlers. Because the document must be loaded, either locally or remotely, a
java.io.IOException can result, and must be caught. In addition, the org.xml.
sax.SAXException can be thrown if problems occur while parsing the document. So we can
add two more import statements and a few lines of code, and have an application that parses
XML ready to use: import java.io.IOException; import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
http://csetube.co.nr/
GKMCET
Lecture Plan
/
these changes and you are ready to execute the parsing example. You should specify the full
nr
o.
path to your file as the first argument to the program: D:\prod\JavaXML> java
e.c
SAXParserDemo D:\prod\JavaXML\contents\contents.xml Parsing XML File:
ub
the parse() method may also be invoked with an org. xml.sax.InputSource as an argument.
cs
://
There is actually remarkably little to comment on in regard to this class; it is used as a helper
tp
and wrapper class more than anything else. An InputSource simply encapsulates information
ht
about a single object. While this isnt very helpful in our example, in situations where a
system identifier, public identifier, or a stream may all be tied to one URI, using an
InputSource for encapsulation can become very handy. The class has accessor and mutator
methods for its system ID and public ID, a character encoding, a byte stream
(java.io.InputStream), and a character stream (java.io.Reader). Passed as an argument to the
parse() method, SAX also guarantees that the parser will never modify the InputSource.
http://csetube.co.nr/
GKMCET
Lecture Plan
/
you to convert the data to other XML documents or to other formats, such as HTML. JAXP
nr
o.
also provides namespace support, allowing you to work with schemas that might otherwise
e.c
have naming conflicts. Designed to be flexible, JAXP allows you to use any XML-compliant
ub
parser from within your application. It does this with what is called a pluggability layer,
et
which allows you to plug in an implementation of the SAX or DOM APIs. The pluggability
cs
://
layer also allows you to plug in an XSL processor, which lets you transform your XML data
tp
http://csetube.co.nr/
GKMCET
Lecture Plan
The default implementations of the methods that the parser calls do nothing, so you need to
write a subclass implementing the appropriate methods to get the functionality you want. For
example, suppose you want to get the price per pound for Mocha Java. You would write a
class extending DefaultHandler (the default implementation of ContentHandler) in which you
write your own implementations of the methods startElement and characters.. In this
example, the price list is a file, but the parse method can also take a variety of other input
sources, including an InputStream object, a URL, and an InputSource object.
SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser =
/
factory.newSAXParser();
nr
o.
saxParser.parse("priceList.xml", handler);
e.c
The result of calling the method parse depends, of course, on how the methods in handler
ub
were implemented. The SAX parser will go through the file priceList.xml line by line, calling
et
the appropriate methods. In addition to the methods already mentioned, the parser will call
cs
://
processingInstructions, but these methods still have their default implementations and th met.
ht
Note that the SAX parser will have to invoke both methods more than once before the
conditions for printing the price are met. public void startElement(..., String elementName,
...){ if(elementName.equals("name")){ inName = true; } else if(elementName.equals("price")
&& inMochaJava ){ inPrice = true; inName = false; }
} public void characters(char [] buf, int offset, int len) { String s = new String(buf, offset,
len); if (inName && s.equals("Mocha Java")) { inMochaJava = true; inName = false; } else if
(inPrice) { System.out.println("The price of Mocha Java is: " + s); inMochaJava = false;
inPrice = false; } }
}
Once the parser has come to the Mocha Java coffee element, here is the relevant state after
the following method calls:
next invocation of startElement -- inName is true
next invocation of characters -- inMochaJava is true
next invocation of startElement -- inPrice is true
http://csetube.co.nr/
GKMCET
Lecture Plan
/
nr
o.
e.c
ub
et
cs
://
tp
ht
http://csetube.co.nr/
GKMCET
Lecture Plan
The SAX parser can perform validation while it is parsing XML data, which means that it
checks that the data follows the rules specified in the XML document's schema. A SAX
parser will be validating if it is created by a SAXParserFactory object that has had validation
turned on. This is done for the SAXParserFactory object factory in the following line of code.
factory.setValidating(true);
So that the parser knows which schema to use for validation, the XML document must refer
to the schema in its DOCTYPE declaration. The schema for the price list is priceList.DTD,
so the DOCTYPE declaration should be similar to this:
/
<!DOCTYPE PriceList SYSTEM "priceList.DTD">
nr
The DOM API
o.
e.c
The Document Object Model (DOM), defined by the W3C DOM Working Group, is
ub
a set of interfaces for building an object representation, in the form of a tree, of a parsed
et
XML document. Once you build the DOM, you can manipulate it with DOM methods such
cs
://
as insert and remove, just as you would manipulate any other tree data structure. Thus, unlike
tp
a SAX parser, a DOM parser allows random access to particular pieces of data in an XML
ht
document. Another difference is that with a SAX parser, you can only read an XML
document, but with a DOM parser, you can build an object representation of the document
and manipulate it in memory, adding a new element or deleting an existing one.
The following code fragment creates a DocumentBuilderFactory object, which is then used to
create the DocumentBuilder object builder. The code then calls the parse method on builder,
passing it the file priceList.xml. DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance(); DocumentBuilder builder =
factory.newDocumentBuilder();
Document document = builder.parse("priceList.xml");
At this point, document is a DOM representation of the price list sitting in memory. The
following code fragment adds a new coffee (with the name "Kona" and a price of "13.50") to
the price list document. Because we want to add the new coffee right before the coffee whose
name is "Mocha Java", the first step is to get a list of the coffee elements and iterate through
the list to find "Mocha Java". Node rootNode = document.getDocumentElement(); NodeList
http://csetube.co.nr/
GKMCET
Lecture Plan
list = document.getElementsByTagName("coffee"); // Loop through the list. for (int i=0; i <
list.getLength(); i++) { thisCoffeeNode = list.item(i);
/
nr
o.
e.c
ub
et
cs
://
tp
ht
http://csetube.co.nr/
GKMCET
Lecture Plan
/
document.createElement("price"); Text tpNode = document.createTextNode("13.50");
nr
o.
newPriceNode.appendChild(tpNode); newCoffeeNode.appendChild(newNameNode);
e.c
newCoffeeNode.appendChild(newPriceNode); rootNode.insertBefore(newCoffeeNode,
ub
thisCoffeeNode); break;
et
}
cs
://
Note that this code fragment is a simplification in that it assumes that none of the nodes it
tp
XML Namespaces
All the names in a schema, which includes those in a DTD, are unique, thus avoiding
ambiguity. However, if a particular XML document references multiple schemas, there is a
possibility that two or more of them contain the same name. Therefore, the document needs
to specify a namespace for each schema so that the parser knows which definition to use
when it is parsing an instance of a particular schema.
There is a standard notation for declaring an XML Namespace, which is usually done in the
root element of an XML document. In the following namespace declaration, the notation
xmlns identifies nsName as a namespace, and nsName is set to the URL of the actual
namespace: <priceList xmlns:nsName="myDTD.dtd"
xmlns:otherNsName="myOtherDTD.dtd">
http://csetube.co.nr/
GKMCET
Lecture Plan
...
</priceList>
Within the document, you can specify which namespace an element belongs to as follows:
<nsName:price> ...
To make your SAX or DOM parser able to recognize namespaces, you call the method
setNamespaceAware(true) on your ParserFactory instance. After this method call, any parser
that the parser factory creates will be namespace aware.
The XSLT API
/
XML Stylesheet Language for Transformations (XSLT), defined by the W3C XSL Working
nr
o.
Group, describes a language for transforming XML documents into other XML documents or
e.c
into other formats. To perform the transformation, you usually need to supply a style sheet,
ub
which is written in the XML Stylesheet Language (XSL). The XSL style sheet specifies how
et
the XML data will be displayed, and XSLT uses the formatting instructions in the style sheet
cs
://
to perform the transformation. JAXP supports XSLT with the javax.xml.transform package,
tp
http://csetube.co.nr/
GKMCET
Lecture Plan
/
a file for the HTML output, and then finally obtaining the Transformer object transformer
nr
o.
from the TransformerFactory object tFactory. TransformerFactory tFactory =
e.c
TransformerFactory.newInstance(); String stylesheet = "prices.xsl"; String sourceId =
ub
tFactory.newTransformer(new StreamSource(stylesheet));
tp
The transformation is accomplished by invoking the transform method, passing it the data
ht
http://csetube.co.nr/
GKMCET
Lecture Plan
/
Stylesheet) Programming is the Next Generation of the CSS (Cascading Style Sheet
nr
o.
Programming). In CSS, users can use certain style tags which the browsers can understand
e.c
and are predefined by W3 consortium. XSL takes ths to one step ahead and users can define
ub
any tags in the XML file. XML sheets can help in showing the same data in different formats.
et
For example the same data can be shown to different users with different colors and different
cs
://
fonts as required, based on login or personal preferences.In the XML file, reference to the
tp
Style sheet to be used is given using the Following syntax. <?xml-stylesheet href="doc.xsl"
ht
type="text/xsl"?>
Here we are referring to a style sheet called doc.xsl. If the Stylesheet exists in the same
directory as the XML file, then no extra parameters are required while defining Stylesheet. If
it exists at a different location, then you can declare it as http://www.<your
sitelocation.com/styles/doc.xsl.The next parameter indicates that the page to be shown out is
a StyleSheet. For properly viewing the page, in the MIME types definitions under your
Application server, you need to map XSL handler to use text/html. For example in Orion
Server (http://www.orionserver.com), the Servlet which handles XSL requests is
http://csetube.co.nr/
GKMCET
Lecture Plan
/
<xsl:apply-templates/> </font></b> </xsl:template> Here as soon as the Tag "showbold" is
nr
o.
encountered in the XML file, then automatically the Text is replaced with Different Font size
e.c
and color in bold. This is just an example. In real time, some tags, will be creating Table and
ub
show the Data in a well formatted way. Also note that tag "showbold" is not part of the
et
standard HTML and here you have defined a Custom Tag. <?xml version='1.0'?>
cs
://
The next image shows how the input elements presented in the list are filtered depending on
the context node. The template selects the "personnel", the xsl:for-each selects "person"
elements. The "person" element is thus the context for the evaluation of the test. The context
http://csetube.co.nr/
GKMCET
Lecture Plan
is further changed by the partial XPath expression edited so far, the result being the "family"
added to the completion list. Content completion offers the list of components from
included/imported XSLT stylesheets
The content completion offers XSLT variables, templates, functions and modes not only from
the current stylesheet but also from the included or imported ones.
Allow Different Element Colors Depending on XML Prefix
This allows for instance to have the XSLT elements in a different color than the result
elements, or the XML schema elements different from the elements used inside annotations.
/
You can add your own prefixes to the list of prefix to color mappings. In the next image, the
nr
o.
"fo" prefix has been mapped to green.
e.c
XSLT Input Document View
ub
This view presents the tree structure of the XML document set as input for the current
et
stylesheet in the associated transformation scenario. You can create templates or other XSLT
cs
://
snippets by dragging the nodes from the tree into the stylesheet. The generated XPath
tp
expressions are context aware. For example dragging the node "/personnel/person/name" into
ht
a xsl:template matching "person" will insert for instance an "xsl:for-each" with the select
attribute equal to "name", while dragging the same node into a template matching
"personnel", will set a "person/name" as value of the select attribute.
http://csetube.co.nr/
GKMCET
Lecture Plan
4.8 SELECTING XML DATA:XPATH XPath is used to navigate through elements and
attributes in an XML document.XPath is a major element in W3C's XSLT standard - and
XQuery and XPointer are both built on XPath expressions.
XPath : Introduction
XPath is a language for finding information in an XML document.
What You Should Already Know
Before you continue you should have a basic understanding of the following:
HTML / XHTML
/
XML / XML Namespaces
nr
o.
e.c
If you want to study these subjects first, find the tutorials on our Home page.
ub
WHAT IS XPATH?
et
document
tp
XML documents
XPath contains a library of standard functions
XPath is a major element in XSLT
XPath is a W3C recommendation
http://csetube.co.nr/