Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 3: The Client Tier (10 Hrs.)

Similar presentations


Presentation on theme: "Unit 3: The Client Tier (10 Hrs.)"— Presentation transcript:

1 Unit 3: The Client Tier (10 Hrs.)
Representing content; Introduction to XML; Elements and Attributes; Rules for Writing XML; Namespaces; Schema: Simple Types and Complex Types, XSD attributes, default and fixed values, Facets, Use of Patterns, order indicators(All, Choice, Sequences), Occurrence Indicators ( MaxOccurs, MinOccurs), DTD: Internal Declaration, Private External Declaration, Public External Declaration, Defining Elements and Attributes; XSL/XSLT; XPath; XQuery; SAX; DOM

2 XML- DTD (Document Type Declaration)
Describe XML language precisely. Check vocabulary and validity of the structure of XML documents against grammatical rules of appropriate XML language. Can be either specified inside the document, or it can be kept in a separate document and then liked separately.

3 Basic syntax of a DTD <!DOCTYPE element DTD identifier [ ]>
declaration1 declaration2 ]> In the above syntax, The DTD starts with <!DOCTYPE delimiter. An element tells the parser to parse the document from the specified root element. DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called External Subset. The square brackets [ ] enclose an optional list of entity declarations called Internal Subset.

4 Internal DTD Elements are declared within the XML files.
standalone attribute in XML declaration must be set to yes. Syntax: <!DOCTYPE root-element [element-declarations]> here root-element is the name of root element and element-declarations is where you declare the elements.

5 Example of internal DTD
<?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>Your Name</name> <company>XYZ Company</company> <phone>(011) </phone> </address>

6 Start Declaration- Begin the XML declaration with <. xml version="1
Start Declaration- Begin the XML declaration with <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> DTD- document type declaration follows, commonly referred to as the DOCTYPE: <!DOCTYPE address [ The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The DOCTYPE informs the parser that a DTD is associated with this XML document. DTD Body- Declare elements, attributes, entities, and notations: <!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone_no (#PCDATA)> Several elements are declared here that make up the vocabulary of the <name> document. <!ELEMENT name (#PCDATA)> defines the element name to be of type "#PCDATA". Here #PCDATA means parse-able text data. End Declaration - DTD is closed using a closing bracket and a closing angle bracket (]>).

7 Rules for Internal DTD The document type declaration must appear at the start of the document (preceded only by the XML header) — it is not permitted anywhere else within the document. Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark. The Name in the document type declaration must match the element type of the root element.

8 External DTD Elements are declared outside the XML file.
Accessed by specifying the system attributes which may be either the legal .dtd file or a valid URL. standalone attribute in the XML declaration must be set as no. Syntax: <!DOCTYPE root-element SYSTEM "file-name"> here file-name is the file with .dtd extension.

9 <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE address SYSTEM "address.dtd"> <address> <name>Your Name</name> <company>XYZ Company</company> <phone>(011) </phone> </address> The content of the DTD file address.dtd are as shown: <!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone (#PCDATA)>

10 Refer to an external DTD by using either system identifiers or public identifiers.
A system identifier enables you to specify the location of an external file containing DTD declarations. Syntax: <!DOCTYPE name SYSTEM "address.dtd" [...]>

11 PUBLIC IDENTIFIERS Public identifiers provide a mechanism to locate DTD resources and are written as below: <!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN"> Followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format, however, a commonly used format is called Formal Public Identifiers, or FPIs.

12 XML Schema Also known as XML Schema Definition (XSD).
Used to describe and validate the structure and the content of XML data. Defines the elements, attributes and data types. Schema element supports Namespaces. Similar to a database schema that describes the data in a database. Describe the legitimate format that an XML document can take.

13 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
Syntax: <xs:schema xmlns:xs=" Example <?xml version="1.0" encoding="UTF-8"?> <xs:element name="contact"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string" /> <xs:element name="company" type="xs:string" /> <xs:element name="phone" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

14 Element Defined as building blocks of an XML.
Elements can behave as containers to hold text, elements, attributes, media objects or all of these. An element can be defined within an XSD as follows: <xs:element name="x" type="y"/> XML Schema has a lot of built-in data types. The most common types are: xs:string, xs:decimal, xs:integer, xs:boolean, xs:date, xs:time.

15 Definition Types of XML Schema Elements
Simple Type: Used only in the context of the text. Some of predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example: <xs:element name="phone_number" type="xs:int" />

16 It is a container for other element definitions.
2. Complex Type: It is a container for other element definitions. Allows to specify which child elements an element can contain and to provide some structure within XML documents. Example: <xs:element name="Address"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string" /> <xs:element name="company" type="xs:string" /> <xs:element name="phone" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> Here, Address element consists of child elements. This is a container for other <xs:element> definitions, that allows to build a simple hierarchy of elements in the XML document.

17 Example: To generalize the person and company
3. Global Types Defining a single type in document, which can be used by all other references. Example: To generalize the person and company for different addresses of the company. In such case, we define a general type as below: <xs:element name="AddressType"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string" /> <xs:element name="company" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element>

18 <xs:element name="Address1">
<xs:complexType> <xs:sequence> <xs:element name="address" type="AddressType" /> <xs:element name="phone1" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="Address2"> <xs:element name="phone2" type="xs:int" /> Instead of having to define the name and the company twice (once for Address1 and once for Address2), we now have a single definition. This makes maintenance simpler, i.e., if you decide to add "Postcode" elements to the address, you need to add them at just one place.

19 Attributes Attributes in XSD provide extra information within an element. Attributes have name and type property as shown below: <xs:attribute name="x" type="y"/> Example: XML element with an attribute: <lastname lang="EN">Smith</lastname> And corresponding attribute definition: <xs:attribute name="lang" type="xs:string"/>

20 Default Values for Attributes
A default value is automatically assigned to the attribute when no other value is specified. Example: <xs:attribute name="lang" type="xs:string" default="EN"/> The default value is "EN"

21 Fixed Values for Attributes
A fixed value is also automatically assigned to the attribute, and you cannot specify another value. Example: <xs:attribute name="lang" type="xs:string" fixed="EN"/> The fixed value is "EN"

22 Optional and Required Attributes
Attributes are optional by default. To specify that the attribute to required, use the "use" attribute: <xs:attribute name="lang" type="xs:string" use="required"/>

23 Facets Restrictions on XML elements.
Restrictions are used to define acceptable values for XML elements or attributes. If an XML element is of type "xs:date" and contains a string like "Hello World", the element will not validate. With XML Schemas, you can also add your own restrictions to your XML elements and attributes.

24 1. Restrictions on Values
The following example defines an element called "age" with a restriction. The value of age cannot be lower than 0 or greater than 120: <xs:element name="age"> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"/> <xs:maxInclusive value="120"/> </xs:restriction> </xs:simpleType> </xs:element>

25 2. Restrictions on a Set of Values
To limit the content of an XML element to a set of acceptable values, we would use the enumeration constraint. The example below defines an element called "car" with a restriction. The only acceptable values are: Audi, Golf, BMW: <xs:element name="car"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Audi"/> <xs:enumeration value="Golf"/> <xs:enumeration value="BMW"/> </xs:restriction> </xs:simpleType> </xs:element>

26 3. Restrictions on a Series of Values
To limit the content of an XML element to define a series of numbers or letters that can be used, we would use the pattern constraint. The example below defines an element called "letter" with a restriction. The only acceptable value is ONE of the LOWERCASE letters from a to z: <xs:element name="letter"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="[a-z]"/> </xs:restriction> </xs:simpleType> </xs:element>

27 <xs:element name="initials">
This example also defines an element called "initials" with a restriction. The only acceptable value is THREE of the LOWERCASE OR UPPERCASE letters from a to z: <xs:element name="initials"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="[a-zA-Z][a-zA-Z][a-zA-Z]"/> </xs:restriction> </xs:simpleType> </xs:element>

28 The only acceptable value is THREE of the UPPERCASE letters from a to z:
<xs:pattern value="[A-Z][A-Z][A-Z]"/> The only acceptable value is ONE of the following letters: x, y, OR z: <xs:pattern value="[xyz]"/> The only acceptable value is FIVE digits in a sequence, and each digit must be in a range from 0 to 9: <xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/>

29 4. Restrictions on Whitespace Characters
To specify how whitespace characters should be handled, we would use the whiteSpace constraint. This example defines an element called "address" with a restriction. The whiteSpace constraint is set to "preserve", which means that the XML processor WILL NOT remove any white space characters: <xs:element name="address"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:whiteSpace value="preserve"/> </xs:restriction> </xs:simpleType> </xs:element>

30 The whiteSpace constraint is set to "replace", which means that the XML processor WILL REPLACE all white space characters (line feeds, tabs, spaces, and carriage returns) with spaces: <xs:whiteSpace value="replace"/> The whiteSpace constraint is set to "collapse", which means that the XML processor WILL REMOVE all white space characters (line feeds, tabs, spaces, carriage returns are replaced with spaces, leading and trailing spaces are removed, and multiple spaces are reduced to a single space: <xs:whiteSpace value="collapse"/>

31 5. Restrictions on Length:
To limit the length of a value in an element, we would use the length, maxLength, and minLength constraints. This example defines an element called "password" with a restriction. The value must be exactly eight characters: <xs:element name="password"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:length value="8"/> </xs:restriction> </xs:simpleType> </xs:element>

32 <xs:element name="password">
This example defines another element called "password" with a restriction. The value must be minimum five characters and maximum eight characters: <xs:element name="password"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:minLength value="5"/> <xs:maxLength value="8"/> </xs:restriction> </xs:simpleType> </xs:element>

33

34 XSD Indicators XSD indicators are used to control how elements are to be used in documents with indicators. There are seven indicators: 1. Order indicators: They contain; All Choice Sequence 2. Occurrence indicators: They include; maxOccurs minOccurs 3. Group indicators: They contain; Group name attributeGroup name

35 1. Order Indicators: Order indicators are used to define the order of the elements. All Indicator The <all> indicator specifies that the child elements can appear in any order, and that each child element must occur only once: <xs:element name="person"> <xs:complexType> <xs:all> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:all> </xs:complexType> </xs:element> Note: When using the <all> indicator you can set the <minOccurs> indicator to 0 or 1 and the <maxOccurs> indicator can only be set to 1

36 Choice Indicator The <choice> indicator specifies that either one child element or another can occur: <xs:element name="person"> <xs:complexType> <xs:choice> <xs:element name="employee" type="employee"/> <xs:element name="member" type="member"/> </xs:choice> </xs:complexType> </xs:element>

37 Sequence Indicator The <sequence> indicator specifies that the child elements must appear in a specific order: <xs:element name="person"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element>

38 2. Occurrence Indicators
Used to define how often an element can occur. Note: For all "Order" and "Group" indicators (any, all, choice, sequence, group name, and group reference) the default value for maxOccurs and minOccurs is 1. maxOccurs Indicator: The <maxOccurs> indicator specifies the maximum number of times an element can occur: <xs:element name="person"> <xs:complexType> <xs:sequence> <xs:element name="full_name" type="xs:string"/> <xs:element name="child_name" type="xs:string" maxOccurs="10"/> </xs:sequence> </xs:complexType> </xs:element>

39 minOccurs Indicator The <minOccurs> indicator specifies the minimum number of times an element can occur: <xs:element name="person"> <xs:complexType> <xs:sequence> <xs:element name="full_name" type="xs:string"/> <xs:element name="child_name" type="xs:string" maxOccurs="10" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> The example above indicates that the "child_name" element can occur a minimum of zero times and a maximum of ten times in the "person" element.

40 An XML file called "Myfamily.xml":
To allow an element to appear an unlimited number of times, use the maxOccurs="unbounded" statement: Consider an example; An XML file called "Myfamily.xml": <?xml version="1.0" encoding="ISO "?> <persons xmlns:xsi=" xsi:noNamespaceSchemaLocation="family.xsd"> <person> <full_name>Anjolina</full_name> <child_name>Janet</child_name> </person> <full_name>Dhritrasta</full_name> <child_name>Duryodhan</child_name> <child_name>Dushasan</child_name> <child_name>Kushashan</child_name> <child_name>Sushasan</child_name> <full_name>Bhismapitamaha</full_name> </persons>

41 Here is the schema file "family.xsd":
The XML file above contains a root element named "persons". Inside this root element we have defined three "person" elements. Each "person" element must contain a "full_name" element and it can contain up to five "child_name" elements. Here is the schema file "family.xsd": <?xml version="1.0" encoding="ISO "?> <xs:schema xmlns:xs=" elementFormDefault="qualified"> <xs:element name="persons"> <xs:complexType> <xs:sequence> <xs:element name="person" maxOccurs="unbounded"> <xs:element name="full_name" type="xs:string"/> <xs:element name="child_name" type="xs:string" minOccurs="0" maxOccurs="5"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

42 3. Group Indicators Group indicators are used to define related sets of elements. Element Groups: Element groups are defined with the group declaration, like this: <xs:group name="groupname"> ... </xs:group> must define an all, choice, or sequence element inside the group declaration.

43 <xs:group name="persongroup">
The following example defines a group named "persongroup", that defines a group of elements that must occur in an exact sequence: <xs:group name="persongroup"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> <xs:element name="birthday" type="xs:date"/> </xs:sequence> </xs:group>

44 <xs:attributeGroup name="personattrgroup">
Attribute Groups: Attribute groups are defined with the attributeGroup declaration, like this: <xs:attributeGroup name="groupname"> ... </xs:attributeGroup> Example: <xs:attributeGroup name="personattrgroup"> <xs:attribute name="firstname" type="xs:string"/> <xs:attribute name="lastname" type="xs:string"/> <xs:attribute name="birthday" type="xs:date"/> </xs:attributeGroup>

45 DTD Vs. XML Schemas XML Schemas are the successors of DTDs. In near future, XML Schemas will be used in most Web applications as a replacement for DTDs because of the following reasons; XML Schemas are extensible to future additions XML Schemas are richer and more powerful than DTDs XML Schemas are written in XML XML Schemas support data types XML Schemas support namespaces DTDs are better for text-intensive applications, while schemas have several advantages for data-intensive workflows. Schemas are written in XML and thusly follow the same rules, while DTDs are written in a completely different language.

46 XSL Language XSL stands for EXtensible Stylesheet Language.
The World Wide Web Consortium (W3C) started to develop XSL. XML does not use predefined tags (we can use any tag-names we like), and therefore the meaning of each tag is not well understood. XSL describes how the XML document should be displayed, however its more than a Style Sheet Language. XSL consists of three parts: XSLT - a language for transforming XML documents XPath - a language for navigating in XML documents XSL-FO - a language for formatting XML documents

47 XSLT (Extensible Stylesheet Language Transformations )
Transforms an XML document into another XML document. Uses XPath to navigate in XML documents. Transforms each XML element into an (X)HTML element. adding/removing elements and attributes to or from the output file can be done. rearrange and sort elements, perform tests and make decisions about which elements to hide and display, and a lot more can be done.

48 XSTL transformation process
XSLT uses XPath to define parts of the source document that should match one or more predefined templates. (XPath is used to navigate through elements and attributes in XML documents.) When a match is found, XSLT will transform the matching part of the source document into the result document. XSLT transforms an XML source-tree into an XML result-tree.

49 Root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or <xsl:transform> The correct way to declare an XSL style sheet according to the W3C XSLT Recommendation is: <xsl:stylesheet version="1.0" xmlns:xsl=" or: <xsl:transform version="1.0" xmlns:xsl=" To get access to the XSLT elements, attributes and features we must declare the XSLT namespace at the top of the document.

50 Consider an example below, which we want to transform the following XML document ("cdcatalog.xml") into XHTML: <?xml version="1.0" encoding="ISO "?> <?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> </catalog>

51 <?xml version="1.0" encoding="ISO-8859-1"?>
We can create an XSL Style Sheet ("cdcatalog.xsl") with a transformation template: <?xml version="1.0" encoding="ISO "?> <xsl:stylesheet version="1.0" xmlns:xsl=" <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

52 In example of cdcatalog.xsl, it can be explained as;
Since an XSL style sheet is an XML document, it always begins with the XML declaration: <?xml version="1.0" encoding="ISO "?>. The next element, <xsl:stylesheet>, defines that this document is an XSLT style sheet document (along with the version number and XSLT namespace attributes). The <xsl:template> element defines a template. The match="/" attribute associates the template with the root of the XML source document. The content inside the <xsl:template> element defines some HTML to write to the output. The last two lines define the end of the template and the end of the style sheet.

53 The <xsl:value-of> Element
The <xsl:value-of> element can be used to extract the value of an XML element and add it to the output stream of the transformation. In the example cdcatalog.xsl, we have used it as; <xsl:value-of select="catalog/cd/title"/> <xsl:value-of select="catalog/cd/artist"/>

54 XSLT <xsl:template> Element:
An XSL style sheet consists of one or more set of rules that are called templates. A template contains rules to apply when a specified node is matched. <xsl:template> element is used to build templates. The match attribute is used to associate a template with an XML element. match attribute is an XPath expression (i.e. match="/" defines the whole document).

55 XSLT <xsl:for-each> Element
Allows to do looping in XSLT. It can be used to select every XML element of a specified node-set. <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:for-each>

56 <xsl:for-each select="catalog/cd[artist='Bob Dylan']">
We can filter the output from the XML file by adding a criterion to the select attribute in the <xsl:for-each> element. <xsl:for-each select="catalog/cd[artist='Bob Dylan']"> Legal filter operators are: = (equal) != (not equal) < less than > greater than In the example of cdcatalog.xsl; we can use restriction as; <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:for-each>

57 The XSL <xls:sort> Element
The <xsl:sort> element is used to sort the output. To sort the output, simply add an <xsl:sort> element inside the <xsl:for-each> element in the XSL file. <xsl:for-each select="catalog/cd"> <xsl:sort select="artist"/> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:for-each>

58 XSL <xls:if> Element
is used to put a conditional test against the content of the XML file. To add a conditional test, add the <xsl:if> element inside the <xsl:for-each> element in the XSL file. Example: <xsl:for-each select="catalog/cd"> <xsl:if test="price > 10"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:if> </xsl:for-each>

59 XSL <xls:choose> Element
The <xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express multiple conditional tests. Example: <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title"/></td> <xsl:choose> <xsl:when test="price > 10"> <td bgcolor="#ff00ff"> <xsl:value-of select="artist"/></td> </xsl:when> <xsl:when test="price > 9"> <td bgcolor="#cccccc"> <xsl:value-of select="artist"/></td> <xsl:otherwise> <td><xsl:value-of select="artist"/></td> </xsl:otherwise> </xsl:choose> </tr> </xsl:for-each>

60 XPath The XML Path Language, is a query language for selecting nodes from an XML document. Language for addressing parts of an XML document, designed to be used by both XSLT and XPointer. XPath uses path expressions to navigate in XML documents. It also contains a library of standard functions for string values, numeric values, date and time comparison etc.

61 XML documents are treated as trees of nodes
XML documents are treated as trees of nodes. The topmost element of the tree is called the root element. XPath uses path expressions to select nodes or node-sets in an XML document. The most useful path expressions are listed below: Expression Description nodename Selects all child nodes of the named node / Selects from the root node // Selects nodes in the document from the current node that match the selection no matter where they are . Selects the current node .. Selects the parent of the current node @ Selects attributes

62 XQuery XQuery is to XML what SQL is to databases.
XQuery is designed to query XML data. XQuery is built on XPath expressions XQuery is supported by all major databases XQuery is a W3C Recommendation Example: for $x in doc("books.xml")/bookstore/book where $x/price>30 order by $x/title return $x/title

63 XQuery is a language for finding and extracting elements and attributes from XML documents.
XQuery can be used to: Extract information to use in a Web Service Generate summary reports Transform XML data to XHTML Search Web documents for relevant information

64 What is FLWOR? FLWOR (pronounced "flower") is an acronym for "For, Let, Where, Order by, Return". For - selects a sequence of nodes Let - binds a sequence to a variable Where - filters the nodes Order by - sorts the nodes Return - what to return (gets evaluated once for every node)

65 SAX(Simple API for XML)
Allows a programmer to interpret a Web file that uses the XML SAX is an alternative to using the Document Object Model (DOM) to interpret the XML file. appropriate where many or very large files are to be processed, but it contains fewer capabilities for manipulating the data content. SAX is an event-driven interface. The programmer specifies an event that may happen and, if it does, SAX gets control and handles the situation. SAX works directly with an XML parser. SAX was developed collaboratively by members of the XML-DEV mailing list (currently hosted by OASIS). Where the DOM operates on the document as a whole, SAX parsers operate on each piece of the XML document sequentially.

66 XML processing with SAX
A Parser that implements SAX (i.e., a SAX Parser) functions as a stream parser, with an event-driven API. The user defines a number of callback methods that will be called when events occur during parsing. The SAX events include (among others): XML Text nodes XML Element Starts and Ends XML processing instructions XML Comments

67 SAX interface does not deal in elements, but in events that largely correspond to tags.
SAX parsing is unidirectional; previously parsed data cannot be re-read without starting the parsing operation again. Example: <?xml version="1.0" encoding="UTF-8"?> <DocumentElement param="value"> <FirstElement> ¶ Some Text </FirstElement> <?some_pi some_attr="some_value"?> <SecondElement param2="something"> Pre-Text <Inline>Inlined text</Inline> Post-text. </SecondElement> </DocumentElement>

68 This XML document, when passed through a SAX parser, will generate a sequence of events like the following: XML Element start, named DocumentElement, with an attribute param equal to "value" XML Element start, named FirstElement XML Text node, with data equal to "¶ Some Text" (note: certain white spaces can be changed) XML Element end, named FirstElement Processing Instruction event, with the target some_pi and data some_attr="some_value" (the content after the target is just text; however, it is very common to imitate the syntax of XML attributes, as in this example) XML Element start, named SecondElement, with an attribute param2 equal to "something" XML Text node, with data equal to "Pre-Text" XML Element start, named Inline XML Text node, with data equal to "Inlined text" XML Element end, named Inline XML Text node, with data equal to "Post-text." XML Element end, named SecondElement XML Element end, named DocumentElement

69 DOM(Document Object Model)
Is a W3C standard. Defines a standard for accessing documents like HTML and XML. Definition of DOM as put by the W3C is: “The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.”

70 Defines the objects and properties and methods (interface) to access all XML elements.
XML documents have a hierarchy of informational units called nodes; DOM is a standard programming interface of describing those nodes and the relationships between them. Provides an API that allows a developer to add, edit, move or remove nodes at any point on the tree in order to create an application.

71 Below is the diagram for the DOM structure which depicts that parser evaluates an XML document as a DOM structure by traversing through each nodes.

72 Advantages XML DOM is language and platform independent. XML DOM is travesible - Information in XML DOM is organized in a hierarchy which allows developer to navigate around the hierarchy looking for specific information. XML DOM is modifiable - It is dynamic in nature providing developer a scope to add, edit, move or remove nodes at any point on the tree. Disadvantages It consumes more memory (if the XML structure is large) as program written once remains in memory all the time until and unless removed explicitly. Due to the larger usage of memory its operational speed, compared to SAX is slower.

73 List of the node types and which node types they may have as children
Document -- Element (maximum of one), ProcessingInstruction, Comment, DocumentType (maximum of one) DocumentFragment -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference EntityReference -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference Element -- Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference Attr -- Text, EntityReference ProcessingInstruction -- no children Comment -- no children Text -- no children CDATASection -- no children Entity -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference Notation -- no children

74 Example:node.xml <?xml version="1.0"?> <Company>
<Employee category="technical"> <FirstName>Tanmay</FirstName> <LastName>Patil</LastName> <ContactNo> </ContactNo> </Employee> <Employee category="non-technical"> <FirstName>Taniya</FirstName> <LastName>Mishra</LastName> <ContactNo> </ContactNo> </Company>

75 Document Object Model of the XML document

76 The topmost node of a tree is called the root
The topmost node of a tree is called the root. The root node is <Company> which in turn contains the two nodes of <Employee>. These nodes are referred to as child nodes. The child node <Employee> of root node <Company>, in turn consists of its own child node (<FirstName>, <LastName>, <ContactNo>). The two child nodes, <Employee> have attribute values Technical and Non-Technical, are referred as attribute nodes. The text within the every node is called as text node.

77 The node objects at the same level are called as siblings.
Node object can have only one parent node object. This occupies the position above all the nodes. Here it is Company. The parent node can have multiple nodes called as child nodes. These child nodes can have additional node called as attribute node. In the above example we have two attribute nodes Technical and Non-Technical. The attribute node is not actually a child of the element node, but is still associated with it. These child nodes in turn can have multiple child nodes. The text within the nodes is called as text node. The node objects at the same level are called as siblings. The DOM Identifies: the objects to represent the interface and manipulate the document. the relationship among the objects and interfaces.

78 Accessing Nodes Access a node in three ways:
By using the getElementsByTagName() method. By looping through (traversing) the nodes tree. By navigating the node tree, using the node relationships.

79 <!DOCTYPE html> <html> <body> <div> <b>FirstName:</b> <span id="FirstName"></span><br> <b>LastName:</b> <span id="LastName"></span><br> <b>ContactNo:</b> <span id="ContactNo"></span><br> <b> </b> <span id=" "></span> </div> <script> //if browser supports XMLHttpRequest if (window.XMLHttpRequest) {// Create an instance of XMLHttpRequest object. code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // sets and sends the request for calling "node.xml" xmlhttp.open("GET","/dom/node.xml",false); xmlhttp.send(); // sets and returns the content as XML DOM xmlDoc=xmlhttp.responseXML; //parsing the DOM object document.getElementById("FirstName").innerHTML= xmlDoc.getElementsByTagName("FirstName")[0].childNodes[0].nodeValue; document.getElementById("LastName").innerHTML= xmlDoc.getElementsByTagName("LastName")[0].childNodes[0].nodeValue; document.getElementById("ContactNo").innerHTML= xmlDoc.getElementsByTagName("ContactNo")[0].childNodes[0].nodeValue; document.getElementById(" ").innerHTML= xmlDoc.getElementsByTagName(" ")[0].childNodes[0].nodeValue; </script> </body> </html>

80


Download ppt "Unit 3: The Client Tier (10 Hrs.)"

Similar presentations


Ads by Google