This document was ed by and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this report form. Report 3b7i
RATIONALE Why This Module Data interchange is essential to carry out business transactions. The challenge in carrying out data interchange lies in establishing standard interfaces among enterprises with related business interests or groups within an enterprise, in which the data is stored in disparate forms. XML provides a structure for storing data in text format, which can be used as a standard format or protocol for data interchange. It plays an extended role as a very robust data interchange format which is essential for various applications. XML allows creation of custom markup tags, thereby providing flexibility to define structure of the content and also describe the content. This flexibility of XML has enabled chemical, cellular, mobile, and many more industries to describe and define the content according to their requirements. Chemical Markup language, Wireless Markup Language, Math Markup Language are examples of industry specific markup languages developed using XML. They allow definition and description of industry specific data. For example, molecules, atoms, and elements can all now be defined and described using the Chemical Markup Language. Similarly, complex mathematical equations, such as calculations, can be represented using Math Markup languages. SMIL is one such markup language, which allows integration of media such as audio and video into Web pages. Thus, XML serves as an enabling technology for many other technologies. XML stores data in device-independent format. XML documents can be exchanged over the Web. This enables usage of XML for all e-commerce transactions on the Web. ebXML is the latest XML-based markup language aiming to define and develop standards for electronic business and data exchange between businesses on the Web. Software programs, applications, and environments, such as Microsoft Office XP and Microsoft .Net framework, XML extensively. In addition, relational database management systems such as SQL Server 2000 allow generation of XML documents. Software giants like IBM, Oracle and Sun Microsystems are also integrating their products with XML. Therefore, XML is fast emerging as a standard technology to describe and define documents. In this module, students will be introduced to the features of XML and its advantages over traditional electronic data interchange (EDI). Students will also learn about various XML-related specifications, such as Document Type Definitions, XML schemas, eXtensible Style Sheet Language Transformations (XSLT), XPath, XML Document Object Model, and Xlink and XPointer. During this module, students will learn to create well-formed and valid XML documents. They will also learn to format XML documents by using Cascading Style Sheets (CSS) and XSLT. Then, they will learn to access various parts of an XML document through JavaScript by using XML Document Object Model.
OBJECTIVES Besides introducing students to the fundamentals of XML, this module will familiarize them with the following:
Using XML as a standard data interchange format Creating a well-formed XML document Creating Document Type Definitions (DTD) and XML schemas for ensuring the consistency in the structure of XML documents
Using namespaces in XML documents for avoiding conflicting element names Formatting XML documents by using style sheets x
Cascading Style Sheets (CSS)
x
eXtensible Style Sheet Language Transformations (XSLT)
Using Xpath patterns and functions for querying XML documents Accessing different parts of an XML document by using XML Document Object Model (DOM) At the end of the XML module, the student should be comfortable with the basic concepts of XML and also be able to effectively use XML as a markup language to develop Web applications.
ENTRY PROFILE A student who s for the XML module should be able to perform the following tasks:
Create Web pages by using HTML Write code in JavaScript for handling various events Identify features of OOP Work in Windows environment Create and maintain documents by using an editor and perform simple editing tasks Interact in English in a classroom environment
EXIT PROFILE At the end of this module, the student will be able to:
Design XML documents Define schemas and validation rules for XML documents using the DTD and XSD languages Write stylesheet programs to transform the data present in an XML document Write programs using JavaScript and DOM to access XML documents Skills Acquired Create well-formed XML documents Use DTD to define XML documents Create XML documents and validate them against the DTD Use XSD to define XML documents Create XML documents and validate them against the schema Use XSL to transform XML documents and present the data in the Web browser Use JavaScript and DOM to access and manipulate data present in an XML document
What is XML? Extensible Markup Language (XML) is a way of structuring data on the Web. Using XML, you can create your own markup language. HTML concentrates on the presentation of data on the Web. For example, when you use the
tag of HTML, the browser interprets it as a paragraph and displays the text within the tags accordingly. XML, on the other hand, does not have any predefined tags. XML concentrates on the content within the tags. For example, for representing customer information, you can create your own tag,
. XML is a text-based format that lets developers describe, deliver, and exchange data between different applications. It is a database- and device-neutral format. It stores data in a structured text format, which can be easily used by any computerized system. XML s UNICODE as well and hence will help internationalize the World Wide Web.
2.
Who invented XML? XML is designed by a working group of the World Wide Web Consortium (W3C), which is an organization that aims at leading the WWW to its full potential by developing common protocols that promote the World Wide Web and ensure its interoperability. The XML development effort started in 1996 led by Jon Bosak of Sun Microsystems. Bosak organized a diverse group of markup language experts, from industry to academia, to develop a simplified version of SGML (Standard Generalized Markup Language) for the Web. In February 1998, XML 1.0 specification became a recommendation by the W3C. Today, the XML Working Group consists of 14 companies and organizations, including Adobe, ArborText, DataChannel, Fuji Xerox, Hewlett-Packard, Inso, Isogen, Microsoft, Netscape, SoftQuad, and Sun Microsystems.
3.
Will XML replace HTML? No. XML is not going to replace anything that you have learned. XML complements it. You can use XML to create your own tags and then use HTML tags to format the data in XML document. You can use Cascading Style Sheets to define the font colors and the position of text within the tags in an XML document.
4.
What are the XML-related specifications? XML is defined by the following specifications: XML 1.0 defines the syntax of XML. XML Pointer Language (XPointer) and XML Linking Language (XLink) define the standard way of representing links between various resources. Extensible Style Sheet language (XSL) defines the style sheet language for XML. The specifications for namespaces, XML Query Language, and XML Schema are being actively pursued.
5.
What are the key benefits of XML? XML simplifies data interchange. It also reduces the cost involved in interchanging data between different applications. It is a plain text format that can be understood by different software and hardware platforms. Therefore, you do not require any special software for reading XML data. XML is flexible and extensible, unlike traditional EDI, which had rigid transaction sets. XML
allows you to easily introduce new tags and thereby create structured documents based on business requirements. XML also provides for Unicode. This feature allows you to create applications that provide global language . 6.
What are the applications of XML? XML is poised to play a prominent role as a data interchange format in electronic business Web applications such as e-commerce, supply-chain management, and application integration. Another use of XML is for structured information management, including information from databases. XML also s media-independent publishing, allowing documents to be written once and published in multiple media formats and devices. On the client side, XML can be used to create customized views of data based on requirements. In case of the middle layer, XML is fast emerging as a standard data interchange format between applications and various components. For example, Microsoft .Net framework has introduced Web services, which use XML for communication with the client application. A Web service is a piece of code that can be accessed by using Internet protocols, such as the Hypertext Transfer Protocol (HTTP). A Web service is similar to a component, which provides some functionality that can be accessed without knowing about its implementation. However, components have a limitation. They use object-model specific protocols, such as Internet Inter-ORB Protocol (IIOP) and Remote Method Invocations (RMI), for communication. As against this, a Web service uses standard Internet protocols such as HTTP and standard data formats such as eXtensible Markup Language (XML) for communication over the Internet.
7.
What is the relationship between XML and the Java technology? XML and the Java technology are complementary. Java is a platform-independent programming language and XML is a platform-independent data interchange format. Java provides the portable, maintainable code to process portable, reusable XML data. In addition, XML and Java have a number of shared features that make them the ideal pair for Web computing, including being industry standards, platform-independent, extensible, reusable, Web-centric, and internationalized.
8.
What are the benefits of using the Java technology with XML? The Java technology offers a substantial productivity boost for software developers compared to programming languages such as C or C++. In addition, developers using the Java platform can create sophisticated programs that are reusable and maintainable across diverse software and hardware platforms compared to programs written with scripting languages. Using XML and Java together, developers can build sophisticated, interoperable Web applications more quickly and at a lower cost.
9.
What XML technologies are being developed for the Java platform? Sun is actively involved in delivering first-class XML in the Java platform. Through the Java Community Process, two initiatives are in progress: a Java optional package for XML parsing and XML data binding, a project codenamed "Adelard." XML is also used in Java 2 Enterprise Edition (J2EE) as an essential means of information interchange in disparate business systems.
10. What XML-related activities is Sun participating in? Sun is actively participating in W3C working groups for eXtensible Style Sheet Language Transformation (XSLT), XML Schema, XLink, and XML Query. Sun is also participating in a number of other industry consortia including OASIS, XML.org, and Apache. See Sun's XML home page (http://java.sun.com/xml/) for complete information. 11. What is Java API for XML Parsing? The Java API for XML Parsing provides basic functionality for reading, manipulating, and generating XML documents through pure Java Application Programming Interfaces (API). It is a simple API that provides a standard way for any XML conformant parser to be accessed by an
application. Using this software, application and tools developers can build fully functional XMLenabled Java applications for e-commerce, application integration, and Web publishing. 12. What Java runtime environment is required to run the software? The XML Parsing API will run in both JDK 1.1.8 and the Java 2 platform. 13. Is this software compliant with Java Project X? Yes. The JAXP reference implementation (RI) uses the high performance Java Project X as its default parser. 14. What is Java Project X? Java Project X is an experimental technology that provides core XML services written for reading, manipulating and generating XML data. This package features an extremely fast validating and non-validating XML parser that is fully compliant to the W3C XML 1.0 recommendation, SAX 1.0, DOM Level 1 Core, and XML Namespaces. Project X is available for commercial redistribution and can be ed from http://java.sun.com/xml/xml-side1.html. 15. Are there any certifications for XML? Yes. IBM provides certification for XML and related technologies (Test 140). A sample test for this certification is provided at the IBM site, http://www-4.ibm.com/software/ad/certify/sam140.html For more information refer to the site www.ibm.com. 16. What are the pre-requisites for appearing for this certification? This certification recommends the following pre-requisites:
Experience in deg and implementing computer applications. Background in programming/scripting and understanding of basic computer science models
and data structures. In particular, familiarity with XML related computer science concepts like tree traversal, recursion, and reuse of data.
Familiarity with Internet standards and concepts (e.g., Web Browser, client-server, relational databases, documenting, formatting, e-commerce).
17. How will this certification help me? The certification would help you to design and implement applications that make use of XML. It ensures a strong understanding of XML fundamentals and a broad knowledge of XML concepts and related technologies. It also helps in understanding how data relates to XML, in particular with issues associated to information modeling, XML processing, XML rendering, and XML query with a thorough knowledge of core XML related W3C recommendations and is familiar with wellknown best practices. 18. Where can I take this exam? This exam can be taken at any one of the authorized Sylvan Prometric Centre spread worldwide.
LESSON SPECIFIC INPUTS The codes for demos, just a minutes, guided practices, and unguided practices for various lessons are stored under the respective folders in the Data Files folder of the TRM CD. The names of files to be used for each demo/practice are specified at the beginning of each code in the CG.
Lesson One Experiences You can start this session by explaining the need for data interchange and how it affects various applications. As an example, you can discuss B2B e-commerce scenario, where two business partners need to interchange data. Then, introduce electronic data interchange (EDI) and then discuss XML and its role in electronic data interchange in modern applications. You can start the demo section of the lesson by first talking about the information that must be contained in an XML document for the given scenario. You can then explain the various components that make up an XML document. Students must have a very clear understanding of what these components are and how they are used. Next, you can organize the data to be stored as elements, attributes and so on. Finally, the students can be shown the code that is the solution for the given scenario. Please explain each advantage of using XML with an example. This will make it easier for the student to understand the difference between HTML and XML. In the the Solution part of 1.D.1, stress the fact that since XML does not deal with presentation, the data will be displayed along with tags unlike in the case of HTML, where the data was formatted on the basis of the tags used. Tell the students not to bother about the ‘look’ of the data. Just tell them that they will be learning some tools to display formatted data in subsequent sessions. Students should be made to understand the rules that are specified for a well-formed XML document. You can also give them small code snippets and tell students to identify whether the document is wellformed. If the code snippet is not well-formed, ask students to state the reason.
Examples and Analogies While explaining the structure and basic components of an XML document , you can use a simple reallife scenario. This scenario can be based on a conversation between an employer and an employee or between a student and a teacher to enable the student to understand the logical manner in which data is organized in an XML document. You can also compare the syntax and general structure of an XML document with that of an HTML document. For comparing the syntax, you can take a simple example of a letter and write the code in HTML. Then, write the same code by using XML to bring out the difference. While specifying the difference between While explaining internal entities, you can give an example where an attribute should contain the value The name of this book is “If Tomorrow Comes”. In this case, the attribute value contains double quotes embedded within it. To assign this value to an attribute, you would write the following statement:
Sydney Sheldon
Inform the students that details about different types of entities are covered in depth in the appendix. However, to be able to understand how to use the different types of entities, students need to know about DTDs.
Additional Inputs In addition to specifying the version and encoding scheme being used in the XML document, the processing instruction also allows you to specify whether it uses a DTD or not. This is done by using the “standalone” property of the processing instruction. If you set the “standalone” property of the XML document to “yes”, it indicates that the XML document either uses an internal DTD or does not use a DTD at all. If you set the “standalone” property to “no”, it indicates that the XML document uses an external DTD. For more information on internal and external DTDs, refer to Lesson 2 of the Student Guide.
FAQ 1.
Will the XML document produce the correct output even if the PI for the document is missing.? Yes. The PI is optional.
2.
Can the output of an XML document be displayed without a browser ? Yes. You can create an application that displays the output of the XML document in various formats such as message boxes. You can use XML Document Object Model (DOM) for doing so. You will learn about XML DOM in lesson 7 and 8.
3.
What are the applications for which XML can be used? XML is set to play an important role as a data interchange format in electronic business Web applications such as e-commerce and application integration. Another use of XML is for managing structured data, including information from databases. On the client side, XML can be used to create customized views to display data.
Problem-wise Inputs 1.D.1. To execute this demo, open the 1_D_1.xml file in the browser and demonstrate the tree structure of the XML document.
Solutions: Guided Practice 1.P.1. 1_P_1.xml
<TITLE>Morning, Noon, and Night
Sydney
Sheldon
10.00
Lesson Two Experiences You can start this session by talking about the need to ensure consistency of the structure of data while carrying out data interchange. Then, move on to briefly explain how Document Type Definition (DTD) can be used for ensuring consistency of the structure of data. You can then differentiate between a wellformed XML document and a valid XML document, thereby bringing out the importance of DTD. Based on the CyberShoppe scenario, the students must be taught to identify the elements required for storing structured data. The three different types of element content can be explained by using a sample code snippet with all the three types of element content. While explaining how to identify elements and attributes, explain that elements map to nouns and attributes map to adjectives. Bring out the relationship between the two sets to help students understand the concept better. Elements can be declared in the DTD using the statement and attributes can be declared using the statement. Explain the usage of the different symbols that can be used while declaring elements. A situation can be given to students and an exercise on how to use these symbols in the DTD. Inform the students that they can create DTD files by using any text editor, such as Notepad or Editpad. The DTD file should be saved with the dtd extension. The two types of DTD can be explained with a single example, so that students will be able to understand the difference between the two types of DTD. The declaration can be explained in this context. Explain the concept of parsers before explaining the two types of parsers. Give examples for each type of parser. While explaining schemas, state that schemas provide much more control over the type of data that can be stored in elements and attributes in an XML document. Therefore, schemas are being preferred over DTDs in current applications.
Examples and Analogies While explaining the concept of DTD, you can compare it with creating a table in a database. Creating a DTD is similar to creating a table in a database. In DTDs, you specify the structure of data by declaring elements to denote the data. This is similar to creating columns in a table. You can also specify whether providing a value for the element is mandatory or optional. You can then store the data in an XML document that conforms to the DTD for that application. This is similar to adding records in a table.
Problem-wise Inputs 2.D.1 Before you execute this demo, ensure that the Learning Environment folder that is required to validate an XML document against the DTD and a schema is in place. Also ensure that this folder is copied to all student nodes. The files required for this demo are stored as 2_D_1.dtd and 2_D_1.xml. To demonstrate the validation process, open validator.htm in Internet Explorer 5.0 and enter the name of the XML document as 2_D_1.xml. Then, click the Validate link. To demonstrate the types of errors generated if the XML document does not conform to the schema, delete one of the elements from the XML document and run the script in validator.htm again. Let the students notice the type of error generated. Also instruct the students that they must save their documents and the validator.htm script
in the same folder. If these files are not in the same folder, tell them to ensure that they specify the full path of the DTD in the XML document.
2.D.2 To demonstrate the validation of an XML document against a schema, use the Schema Validator. You can do so by opening the index.htm file in IE 5.0 or later. The index.htm file is located in the Learning Environment folder. Click the Schema Validator link. In the resulting form, enter the name of the XML document as 2_D_2.xml. Specify the schema name as 2_D_2.xsd. If the schema does not work properly, the easiest way to find out the problem is by saving the XSD file as an XML document and opening it in the browser. Check whether your XSD schema is well-formed. More than half of the errors can be eliminated by checking whether the schema document is well-formed. If the Schema Validator gives an error stating “Object Required”, please check whether the path specified for the XML file is correct.
Additional Inputs You can add a Browse button to the Learning Environment. You can write a script for allowing students to select a file from the File Open dialog box, instead of making students type the complete path. For example, if you want to include the Browse button in the DTD validator, open DTD.htm in Notepad. This file is located in the Learning Environment folder. Add the following code within the
tags to add a button to the form. Now, add the following script within the and tags: <script language="vbscript"> sub openfile On Error Resume Next Dim CDObj Set CDObj = CreateObject("MSComDlg.CommonDialog") If Err Then MsgBox "Can't create Dialog Object!" End If CDObj.MaxFileSize = 260 ' Init buffer (NECESSARY!) CDObj.Flags = &H1004 ' File Must Exist + no ReadOnly checkbox CDObj.ShowOpen Dim fname fname = CDObj.filename ' Cancel or no file name? If fname <> vbNullString Then document.frmTransform.txtXMLFileName=fname End if document.frmTransform.txtXMLFileName.value=fname msgbox fname Set CDObj = Nothing end sub In the above code, the CommonDialog ActiveX control is used. The CreateObject() method of VBScript is used to create an instance of the CommonDialog control. The ShowOpen() method of this file is used to display the File Open dialog box. When a selects a file name, the selected filename is assigned to the text box in the form. However, the successful execution of the above code depends on the existence of the comdlg32.dll file on a computer.
Can I specify a set of predefined values in an IMPLIED attribute? No. You cannot specify a set of predefined values in an IMPLIED attribute.
2.
What is the difference between REQUIRED and IMPLIED attributes? The main difference between REQUIRED and IMPLIED attributes is that, REQUIRED attributes must be specified each time the element is used whereas IMPLIED attributes are optional.
3.
Can I set a default value for an enumerated value type? Yes. You can set a default value for an enumerated value type. Consider the following example. In the above example, an attribute called CATEGORY is created for the PRODUCT element. The valid values for this attribute are specified as Toy or Book. The default value of this attribute has been set to Book.
4.
What is the difference between the * and + symbol that can be used while defining the DTD? If an * symbol is used, an element can occur zero or multiple times. On the other hand, if a + symbol is used an element must occur at least once.
5.
Can I specify the element anywhere in the DTD or it must necessarily follow the appropriate element declaration? No. You can use the element anywhere in the DTD. But be sure that you use the correct element name.
6.
Can I have more than one ID type of attributes specified for an element in a DTD? No. You cannot define multiple ID attributes on the same element.
Solutions: Just a Minute… 1.
The branches of CyberShoppe send information about books sold by them to the head office. The book details must be stored in a consistent format. Restrictions must be placed on the kind of data that can be saved in the data store to ensure uniformity and consistency of information. The details of books sold by CyberShoppe consist of the name of the book, ISBN of the book, first and last names of the author of the book, and the price of the book. Create a DTD for declaring the elements to be used for storing book details in an XML document. 2_JAM_1.dtd
<xsd:element name="YEAROFRELEASE" type="xsd:string"/> <xsd:simpleType name="mid"> <xsd:restriction base="xsd:string"> <xsd:pattern value="[M]{1}\d{1}\d{1}\d{1}"/> 2_UGP_3.xml <MOVIEDETAILS> <MOVIE> <TITLE>The Sixth Sense <MOVIEID>M876
M Night Shyamalan
Bruce Willis, Haley Joel Osment
1999
Lesson Three Experiences You can begin the session by first explaining to the students that schemas use the same syntax as XML documents. Unlike schemas, DTDs follow their own syntax. Students must have a very clear and thorough understanding of what namespaces are and why they are used in XML, because namespaces are used extensively in XML. You must explain the difference between Web URIs and namespace URIs. Web URIs are used to locate a resource on the Web. They can be used to find the physical location of a resource. On the other hand, namespace URIs just serve the purpose of avoiding conflicting names of elements from two or more DTDs or schemas.
Examples and Analogies Namespace is an abstract concept. Therefore, while explaining the concept of namespaces, talk about a scenario where different programmers might create programs that contain elements that have the same name but store different information. Then, you can discuss about the problems that will arise because of the conflicting element names and how namespaces can be used to solve them. Explain that if there are conflicting element names, the parser will not understand the context in which the elements are to be validated. Therefore, there is an ambiguity. You specify namespaces to eliminate this ambiguity. You can also specify that the prefix used with namespaces is just like an alias. In SQL Server, you use a short name as an alias for a table that has a lengthy name. A namespace prefix serves also serves the same purpose of reducing the time and efforts that would be required to type the complete namespace URI. You must stress the fact that namespaces do not have a physical existence. They are just logical addresses that help you to uniquely identify a component of an XML document.
Problem-wise Inputs The demos for this lesson are stored in Lesson 3\demo folder of the TIRM CD.
3.D.1 The XML file for this demo is called 3_D_1.xml and the XSD file is called 3_D_1.xsd.
3.D.2 The XML file for this demo is called 3_D_2.xml. The common data types are stored in 3_D_2_a.xsd. The schema for the XML document is stored in 3_D_2_b.xsd. To demonstrate the validation process, open Learning Environment\index.htm in the browser. Click the Schema Validator link. Type the name of the XML document as 3_D_2.xml (along with the path) and the name of the XSD file as 3_D_2_b.xsd. If the Schema Validator gives an error stating “Object Required”, please check whether you have specified the correct path for the XML and XSD files.
FAQ 1.
Should a -defined data type be defined immediately after the declaration statement of the attribute or element that it is associated with? No. -defined data types can be defined anywhere in the XSD document. The name attribute of the data type is used to identify the data type. Therefore, it is not necessary for a -defined data type to be defined immediately after an attribute or element declaration statement.
Are there any rules regarding the names that can be use as namespace prefixes? No. You can use any combination of letters as namespace prefixes. However, a short and meaningful namespace prefix can save time and effort on the part of the programmer.
3.
Is there a restriction on the number of times that an attribute can be referenced in an XSD document? No, an attribute can be referenced any number of times in an XSD document.
4.
Can the value attribute of the attribute element be used to specify a list of valid values for the -defined attribute when the use attribute is set to required? No. The value attribute can appear in the attribute declaration statement only when the use attribute is set either to default or fixed.
5.
Is there any equivalent of the ID value type of DTD in XML Schemas? OR How can I ensure that the value of an attribute is unique for every occurrence? The key element of XSD can be used to ensure uniqueness of values contained in an element or an attribute. However, this element does not work with MSXML 4.0 Beta 2.
Solutions: Just a Minute… 1. In addition to storing the name of the book, first and last names of the author, and price of the book, you also need to store the book ID and the type of cover for each book. The type of cover can be either hard or soft. Declare the elements and attributes required to store book details. The book ID can also be used in different XML documents that store products data. Ensure that the book ID attribute is reusable. 3_JAM_1.xsd <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:attribute name="BOOKID" type="xsd:string"/> <xsd:element name="BOOKDATA" type="bodata"/> <xsd:complexType name="bodata"> <xsd:sequence> <xsd:element name="BOOK" type="bk"/> <xsd:complexType name="bk"> <xsd:sequence> <xsd:element name="BOOKNAME" type="xsd:string"/> <xsd:element name="AFNAME" type="xsd:string"/> <xsd:element name="ALNAME" type="xsd:string"/> <xsd:element name="PRICE" type="xsd:positiveInteger"/> <xsd:attribute ref="BOOKID"/> <xsd:attribute name="BOOKCOVER" type="bc" use="required"/> <xsd:simpleType name="bc"> <xsd:restriction base="xsd:string"> <xsd:pattern value="Hard|Soft"/>
The branch offices of CyberShoppe send the details about the sales made by them to the head office. To ensure that the data can be accessed regardless of the hardware and software used at the head office, the branches need to store their data in an XML format. When the head office receives this data, it needs to that all branches have specified all required information. It also needs to that the data sent by various branches is in a consistent format. The sales details sent by various branch offices include the product ID, transaction ID, date of transaction, customer ID, quantity ordered, and price per unit. The product ID, the transaction ID, and the customer ID are used repeatedly in a number of documents. Create reusable data types for storing these details. Also create an XML schema that uses these data types for storing sales details. The product ID should contain the pattern “P[0-9][09][0-9]”.
<element name="DATE" type="date"/> <element name="QUANTITY" type="positiveInteger"/> <element name="PRICEPERUNIT" type="positiveInteger"/>
3_JAM_2.xml <prod:SALES xmlns:prod="www.ecomatcybershop.com/sale" >
2000-02-13
3
20
While validating the above XML document, validate it against 3_JAM_2_b.xml.
Lesson Four Problem-wise Inputs At the end of this lesson, students will work on a comprehensive exercise, which covers all the concepts learned about XML schemas.
Solutions: Just a Minute… 1.
CyberShoppe sells books to its customers. The book details consist of the name of the book, the name of the author of the book, and the price of the book. The name of the authors of the book can be entered either by using the NAME element or by using the FIRSTNAME and LASTNAME elements.
<xsd:complexType name="autype"> <xsd:choice> <xsd:group ref="auname"/> <xsd:element name="NAME" type="xsd:string"/> 4_JAM_1.xml
<TITLE> If Tomorrow Comes
Sydney
Sheldon
20
<TITLE> The Client
John Grisham
20
<xsd:simpleType name="jobtype"> <xsd:restriction base="xsd:string"> <xsd:pattern value= "(CONTRACT|PERMANENT)"/> 4_UGP_3.xml <JOBDETAILS> <JOB JOBID="J001">
Flamingo Inc.
<JOBDESCRIPTION>MKTG MGR <EXPERIENCE>3
<STRICTQUALIFICATION>
Bachelor of Commerce
Business
<EMAIL>
[email protected] <SALARY>5000 <JOBTYPE>PERMANENT <JOB JOBID="J002">
ABC Inc.
<JOBDESCRIPTION>Tech Writing <EXPERIENCE>3
B.A.
<EMAIL>
[email protected] <SALARY>1200 <JOBTYPE>CONTRACT
Lesson Five Experiences You can start this session by talking about rendering and how data can be presented on a variety of targets, such as Web browsers, e-mail, pagers, and cell phones. Talk about the different rendering languages that are used for rendering data to these devices. Besides CSS and XSL, you also have rendering languages such as DSSSL. DSSSL has been covered in the Appendix. It is recommended that you read the section on DSSSL before taking this class. Explain the importance of formatting data before explaining the concept of style sheets. Re-emphasize the fact that XML is a markup language for providing structure to the content and not for presenting data to the . Therefore, you require style sheets.
Both the CSS and XSL files can be created using Notepad and saved with css and xsl extensions, respectively. By using CSS to render data in a browser, the actual data is separated from the information required to present the data. This ensures that the same XML document can be rendered across for purposes, such as printing, displaying data on the Web and making presentations. This does not result in the modification of data as the two are separated. Explain the syntax for coding a CSS file. In order to associate the formatting information to the XML document, students need to use the following syntax in the XML file: To view the output, students need to open the XML file using the browser. While talking about XSL, tell students that CSS cannot be used for performing operations, such as reordering and sorting elements based on a condition. While explaining the working of the XSLT processor, mention that the version of MSXML parser that comes along with IE 5.0 is 2.5. The beta version of MS XML 4.0 parser is currently available at the following site: http://www.microsoft.com/s It is also important to state that the MSXML parser that comes along with IE 5.0 is an older version. Therefore, it does not many of the tags of XSLT. Also, the namespace declarations for old XSL specification is given as follows: <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl"> On the other hand, the newer specification uses the following namespace declaration: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version=“1.0”> You are very likely to face a question from students regarding the XSLT and XPATH Learning Module form. State that we are using this form because IE 5.0 uses MSXML 2.5. Even if you load MSXML 4.0, the newer version runs side-by-side with the older version. Therefore, when you try associate the XSLT document with the XML document, IE 5.0 does not recognize the namespace URI. It still recognizes the old namespace URI. Therefore, you need to use this script. This script loads XML document and XSLT style sheet into various objects and applies the XSLT style sheet to the XML document. Also inform the students that they will learn to write such a script in Lesson 8.
Examples and Analogies The purpose of formatting data and presenting it in different colors and fonts can be explained as a method of gaining the attention of students. For example, while presenting information about ticket details, the name of the wait-listed engers can be presented in a color different from that of the engers whose tickets are confirmed. While explaining sorting of data, you can state that the sort element of XSLT is similar to the ORDER BY clause in SQL Server. Also state that you can have multiple sort elements within a for-each element. Therefore, you can easily sort based on two or more elements.
Can I use both CSS and XSLT together? Yes. You can use XSLT to transform XML data into structures, such as lists or tables, and then apply CSS to the result to control how these structures appear in the appropriate medium.
2.
Where can I use the xsl:sort element? The xsl:sort element can be used as a child for the xsl:for-each element or xsl:apply-templates element.
3.
Why is the xsl:apply-templates element used? The xsl:apply-templates element is used in case of templates-based formatting. The xsl:applytemplates element directs the XSLT processor to find an appropriate xsl:template to apply.
Solutions: Just a Minute… 1.
The details about all the books sold at CyberShoppe are to be displayed in the following format:
The book name is to be displayed in blue color, Times New Roman font, size 20pts, and bold. The first name and last name of the author are to be displayed in green color, Arial font, and size 10pts.
Price of the book is to be displayed in red color, Times New Roman, and size 20pts. Create a CSS for displaying the book details in the above format. 5_JAM_1.xml
ANNE OF GREEN GABLES
LUCY MAUD
MONTGOMERY
150.00
MIND READING IN PUBLIC
ABBOTT
DAVID PHELPS
250.00
THE OUTLET
ADAMS
ANDY
200.00
Lesson Six Experiences You can start this session by explaining the importance of XPath. It is a query language defined for XML that provides a simple syntax to select the subset of nodes in a XML document. XPath treats an XML document as a tree of interrelated branches and nodes, where a node can be any of the following in the document: an element, attribute, processing instruction (PI), comment, text, or namespace. Tell students that XPath expressions can be created using a set of operators and special characters. You can ask students to write a few XPath expressions using these operators and special characters. Talk about the values that an XPath function can return and then discuss about the different types of functions, such as string, node-set, Boolean, and number. By using the operators and the XPath functions, students can calculate data and present it in the form of a summary report. Make sure that the Learning Environment folder is present on all student machines. If the XML and XSLT files are in different folders, ask the students to type in the entire path of these files in the appropriate text boxes of the XSLT and XPATH Learning Module form. You can begin the section on using HTML tags within XSLT by first talking about the limitations of XML with respect to the way in which data is displayed to the . You can then explain the various formatting options ed by HTML.
Examples and Analogies While talking about how XPath treats an XML document as a tree of interrelated branches and nodes, you can compare it with the tree-view of Windows Explorer. Each folder in Windows Explorer can be compared to a node in the tree-view structure of an XML document. You can compare the XPath functions with functions of any other programming language for better understanding. The programming language that you discuss must be based on the batch profile. While explaining the xsl:if and xsl:choose elements, compare them with the if-then construct and switch-case construct respectively.
FAQ 1.
When is the * operator used? The * operator can be used for selecting all elements regardless of the element name. It can also be used for multiplying two numbers.
What does the following code indicate? STUDENTDTLS/STUDENT[@ID='S001'] The given code is a sample XPath expression used for retrieving the STUDENT element, which is a child of the root element, STUDENTDTLS and that has an ID attribute with the value S001.
3.
What does boolean(-100) return? Boolean(-100) will return true.
4.
Why do I get the value “NaN” for some of the calculations that I attempt? NaN stands for Not a Number. This value is usually displayed when calculations are performed on text nodes or the path specified for nodes is not correct. Check your XPath expression if you get this kind of an error.
Solutions: Just a Minute… 1.
The details about books sold at CyberShoppe need to be displayed. Books priced higher than $100 are to be displayed in red color, those priced higher than $75 are to be displayed in blue, and the rest are to be displayed in green color.
6_JAM_1.xml
ANNE OF GREEN GABLES
LUCY MAUD
MONTGOMERY
50.00
MIND READING IN PUBLIC
ABBOTT
DAVID PHELPS
250.00
THE OUTLET
ADAMS
ANDY
76.00
6_JAM_1.xsl <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:for-each select="BOOKDETAILS/BOOK"> <xsl:choose> <xsl:when test="PRICE[. > 100]"> BOOK NAME:<xsl:value-of select="BOOKNAME"/>
AUTHOR: <xsl:value-of select="AFNAME"/> <xsl:text> <xsl:value-of select="ALNAME" />
Solutions: Guided Practice 6.P.1. 6_P_1.xml <SUPPLIERDATA> <SUPPLIER SUPPID="S001">
JANE
PETERSON
10, LIONS RD, BOSTON
344-345-4456
BARBIE DOLL
TOY FOR CHILDREN IN THE AGE GROUP OF 5-10
20
MINI BUS
TOY FOR CHILDREN IN THE AGE GROUP OF 6-11
75
<SUPPLIER SUPPID="S002">
Peter
Mathew
15, LIONS RD, BOSTON
344-345-4346
TEDDY BEAR
TOY FOR CHILDREN IN THE AGE GROUP OF 5-10
10
<SUPPLIER SUPPID="S003">
John
Norton
20, LIONS RD, BOSTON
344-345-2346
BARBIE DOLL
TOY FOR CHILDREN IN THE AGE GROUP OF 5-10
20
<SUPPLIER SUPPID="S004">
Nick
Mathew
25, LIONS RD, BOSTON
344-345-3445
TRAIN
TOY FOR CHILDREN IN THE AGE GROUP OF 5-10
50
USA
608475
6_UGP_4.xsl <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:for-each select="CUSTDETAILS/CUSTOMER">
<xsl:value-of select="@CUSTID"/>
<xsl:value-of select="CUSTNAME"/>
<xsl:value-of select="ADDRESS"/>
<xsl:value-of select="CITY"/>
<xsl:value-of select="STATE"/>
<xsl:value-of select="COUNTRY"/>
<xsl:value-of select="PHONE"/>
Lesson Seven Experiences Introduce the functions of a parser in of its disadvantages, as the parser alone will not allow you to traverse from one portion of the XML document to the other. Then, introduce the Document Object Model (DOM) as a solution for the same. Refer to the latest at www.W3C.org on development of DOM for XML. Instruct the students that the “I” in the IXMLDOMNode, IXMLDOMNodeList, and IXMLDOMParseError objects stands for interface. These are the basic interfaces, which are implemented by various objects of XML DOM.
Solutions: Just a Minute… 1.
The details about products sold at CyberShoppe are stored in an XML document called product.xml. Write the code to display the price of all products by using DOM objects.
7_JAM_1.htm <script language="JavaScript"> function loadXML() { var myxmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0") myxmlDoc.async=false myxmlDoc.load("products.xml") var myelement = myxmlDoc.getElementsByTagName("PRICE"); for (i=0; i<= myelement.length -1; ++i) {
alert(myelement.item(i).text) } } products.xml
Barbie Doll
This is a doll for children aged 11 and above
10
12
Mini Bus
This is a toy for children aged 11 and above
20
12
To execute the script, open the 7_JAM_1.htm page in the browser. As soon as the page is loaded in the browser, it will display message boxes displaying the prices of products. Notice that the getElementsByTagName function is used here to retrieve values of all elements named PRICE. Then, you can display these values by using the for loop to traverse through the node list returned by the getElementsByTagName() function.
Lesson Eight Experiences You can begin the session by giving a brief recap about the various DOM objects discussed in the previous lesson. Ensure that the student understands the main methods and properties that are associated with each of the four objects. You can then explain the scenario that is specified for this lesson. This can be followed by an explanation of the objects that are required to process an XML documents using a style sheet document. First, create the XML and XSD documents. Next, you can talk about the code that is required to process the XML and XSD documents. You can also create the HTML documents that are required to display information to the end . Finally, explain the JavaScript code that must be used to link the various HTML and XML documents.
Examples and Analogies You can compare the working of DOM with that of a linked list. First, explain the different parts of a linked list and the mechanism used to traverse a linked list. You can then compare this process with the way in which the DOM node tree is traversed.
Additional Inputs One of the methods of applying an XSLT style sheet to an XML document is by using the XSLProcessor and XSLTemplate objects. These objects provide the advantages of working on a cached version of style sheets and for asynchronous mode of loading XML document. Another simple way of applying an XSLT style sheet to the XML document is by using the transformNode() method of the DOMDocument object, as shown in the following example: <SCRIPT LANGUAGE="JavaScript"> function LOADXML() { var xmldoc=new ActiveXObject("Msxml2.DOMDocument.4.0"); xmldoc.async=false; xmldoc.load("product.xml"); var xsldoc=new ActiveXObject("Msxml2.DOMDocument.4.0"); xsldoc.async=false; xsldoc.load("productlist.xsl"); x.innerHTML = xmldoc.transformNode(xsldoc); }
The above code creates two instances of the DOMDocument object, one for loading the XML document and the other for loading the XSLT style sheet. Then, it calls the transformNode() method of the
DOMDocument object that contains the XML document and es as an argument a reference of the other DOMDocument that contains the XSLT style sheet. The transformNode() method transforms the XML document into the specified format by applying the style sheet, which is displayed in the browser window. This is another simpler method of dynamically applying an XSLT style sheet to an XML document. However, the transformNode() method is a Microsoft extension to the W3C DOM.
FAQ 1.
What does Msxml2.FreeThreadedDOMDocument stand for? Msxml2.FreeThreadedDOMDocument is used to create a free threaded object. There are two kinds of threading models, rental and free-threaded. The rental model enables for single threaded access in which all objects are executed on a single thread. The free-threaded model enables multithreaded access. In this model, an object can be executed on any thread at any time.
2.
What is cache memory? Cache is a section of the memory of the computer that is made up of high speed Static Random Access Memory (SRAM) Information stored in the cache can be accessed faster than other portions of the RAM.
3.
Is there a method by which I transform a single node? Yes , there is. You can use the transformNode() method of the XMLDOMNode object to transform the information contained in a node and all its child nodes.
Solutions: Just a Minute… 1.
Write the code to add an XML schema called “products.xsd” to a schema collection.
Solution: var xsdschemacache = new ActiveXObject("Msxml2.XMLSchemaCache.4.0"); var xmlDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.4.0"); xmlDoc.validateOnParse=true xmlDoc.load("products.xml"); var namespace=xmlDoc.namespaceURI; xsdschemacache.add(namespace,"products.xsd"); 2.
The following JavaScript code is used create XSLTemplate and DOMDocument objects. Identify the errors in the code, if any. custss = new activexObject(MSXML.XSLTemplate.4) custdomdoc = activexobject( "MSXML.ThreadedDOMdocument.4.0);
Solution: custss= new ActiveXObject("MSXML2.XSLTemplate.4.0"); custdomdoc = new ActiveXObject("MSXML2.FreeThreadedDOMDocument.4.0");
3. Identify the errors in the following JavaScript code: xslProcObject.output=xmlDocObject; xslProcObject.Transform alert("xslProcObject"); Solution: xslProcObject.input=xmlDocObject; xslProcObject.transform(); alert(xslProcObject.output);
Solutions: Guided Practice 8.P.1 The XML document containing the book details is given below: 8_P_1.xml
<TITLE> MORNING, NOON, AND NIGHT
SYDNEY
SHELDON
10
100
<TITLE> THE CLIENT
JOHN
GRISHAM
20
250
<TITLE> A STRANGER IN THE MIRROR
SYDNEY
SHELDON
15
120
To display the above data in a tabular format, you can use the following style sheet: 8_P_1_a.xsl <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/">
In the above code, the xsl:text element is used to add a space between the first name and last name of an author. To display the same book details in a list, you can use the following style sheet: 8_P_1_b.xsl <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:for-each select="BOOKDETAILS/BOOK">
To accept ’s choice of the view, you need to create a Web page containing frames. The left frame will display the controls for accepting input and the right frame will be used for results. For creating a blank page, you can use the following code: right.htm
Untitled Document 6l4kr
The div block in the above code will be used to display the list or table containing book details. You can use the following code for accepting ’s choice: left.htm
Untitled Document 6l4kr <meta http-equiv="Content-Type" content="text/html; charset=iso8859-1"> <script language="javascript">
var xmlDoc function loadXML() { xmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0"); xmlDoc.async = false; xmlDoc.load("8_P_1.xml"); } function ApplyXSL() { var xslt = new ActiveXObject("Msxml2.XSLTemplate.4.0"); var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.4.0"); var xslProc; xslDoc.async = false; alert (stylesheet.value); xslDoc.load(stylesheet.value); xslt.stylesheet = xslDoc; xslProc = xslt.createProcessor(); xslProc.input = xmlDoc; xslProc.transform(); parent.right.x.innerHTML=xslProc.output; } <select name="stylesheet" onChange="ApplyXSL()"> The above code will display a drop-down list box for accepting ’s choice. As soon as the Web page is loaded, the loadXML function is invoked. This function loads the XML document in a DOMDocument object. When a selects one of the options given in the drop-down list box, the onchange event of the SELECT element is fired and the ApplyXSL function is called. This function simply applies appropriate style sheet to the XML document. Finally, you need to create the main page, which will be used to display left.htm and right.htm. <TITLE>XML/XSL Viewer Demo To execute the complete code, open index.htm in the browser and select one of the options from the drop-down list box.
Solutions: Unguided Practice UGP 1. This file accepts the name of the XML file. It provides a text box and a submit hyperlink. On clicking the hyperlink, javascript code loads the XML document. If the XML file is well formed then the javascript function, extracts the elements whose node name is CUSTOMERNAME. The function then loops through the list of nodes returned by the output and if the text enclosed in the elements is "Harold Johnson", the function extracts the ADDRESS and the PHONENUMBER elements and sets the values accordingly and displays the output in a message box. XMLDisplayString.htm
XML 1u3p2l <meta http-equiv="Content-Type" content="text/html; charset=iso8859-1">
<script Language="javascript"> function cmdSubmit_click() { var objelements; if (frmXMLFileName.TxtName.value.length==0) { alert ("Invalid XML String"); } else { var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0"); xmldoc.load(frmXMLFileName.TxtName.value); var error=xmldoc.parseError; if(error!="") { alert("Error");
} } Customer.xml
Harold Johnson
56, Regent Road
London
UK
444-425-2355
UGP 2. This file accepts the name of the XML file. It provides a text box and a submit hyperlink. Clicking the hyperlinks uses dom and javascript to load the xml file. If the xml file is well formed then the JavaScript function, loops through the entire set of nodes present in the xml document using the childNode function and uses the nodeName, nodeType and nodeValue properties of DOMDocument class to display the output in a message box. XMLDisplayString.htm
XML 1u3p2l <meta http-equiv="Content-Type" content="text/html; charset=iso8859-1">
} } movie.xml <MOVIE> <MOVIEID>M920 <MOVIENAME>The Last Emperor
John Lone
Bernado Bertolucci
1987
Drama
UGP 3. The correct code for loading the emp.xml file and applying empss.xsl to it is as follows: <script language="javascript"> var empt = new ActiveXObject("Msxml2.XSLTemplate.4.0"); var emptdoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.4.0"); var empproc; emptdoc.async = false; emptdoc.load("empss.xsl"); empt.stylesheet = emptdoc; var empxml = new ActiveXObject("Msxml2.DOMDocument.4.0"); empxml.async = false; empxml.load("emp.xml"); empproc = empt.createProcessor(); empproc.input = empxml; empproc.transform(); alert(empproc.output);
Solutions to Additional Exercises 1. This solution to the given problem can be achieved using three files, two .xsd files and a .xml file. The files required in the given scenario are as follows: a. commonschema.xsd - This xsd file holds the schema of all the reusable components in the solution. b. casehistory.xsd - This xsd file makes use of commonschema.xsd to define the schema for casehistory.xml c. casehistory.xml - This xml file has CASEHISTORY as the root element with an ID "C001". The information in this xml file is grouped into two elements, PERSONALINFORMATION and CASEINFORMATION. PERSONALINFORMATION stores the NAME,ADDRESS,GENDER,AGE, and EXISTINGDISEASES of a patient. The CASEINFORMATION stores every visit made by the patient to the hospital in the element VISITINFORMATION. The VISITINFORMATION has DATE,DOCTOR,COMPLAIN,DIAGNOSIS, PRESCRIPTION, and NEXTDATEOFVISIT. All the above files are in the same namespace and hence include element is used to include the definitions in commonschema.xsd in casehistory.xsd. Use the XML Schema Validator to validate the xml file against its schema. Casehistory.xml <pat1:CASEHISTORY xmlns:pat1="http://www.Getwellsoon.com/patient" CASESHEETID="C001">
John Watson
24
<STREET>Wellington Road
Seattle
<STATE>Washington
55555
MALE
10
<EXISTINGDISEASES>Diabetes
2001-03-29
Diane
Injury to the left knee caused heavy bleeding
hematoma in left knee
bed rest and change dressing twice a week
2001-04-07
2001-04-07
Diane
Injury to the left knee caused heavy
2. The solution to the given scenario can be achieved using 2 files. Two xsd files and a xml file. The xsd files are: a. casehistory.xsl - This xsl file holds the transformation information to display the xml file. b. casehistory.xml - This xml file has CASEHISTORY as the root element with an ID "C001". The information in this xml file is grouped into two elements - PERSONALINFORMATION and CASEINFORMATION. The PERSONALINFORMATION stores the NAME,ADDRESS,GENDER,AGE, and EXISTINGDISEASES. The CASEINFORMATION stores every visit made by the patient to the hospital in the element VISITINFORMATION. The VISITINFORMATION has DATE,DOCTOR,COMPLAIN,DIAGNOSIS, PRESCRIPTION, and NEXTDATEOFVISIT. The xsl file displays the personal information of the patient in a list and the case related information in a table. Every visit of the patient to the doctor is displayed in a row along with all the information of the patients visit. Casehistory.xml
John Watson
24
<STREET>Wellington Road
Seattle
<STATE>Washington
55555
MALE
10
<EXISTINGDISEASES>Diabetes
2001-03-29
Diane
Injury to the left knee caused heavy bleeding
hematoma in left knee
bed rest and change dressing twice a week
2001-04-07
2001-04-07
Diane
Injury to the left knee caused heavy bleeding
hematoma in left knee
bed rest and change dressing twice a week
2001-04-14
casehistory.xsl <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <xsl:apply-templates/> <xsl:template match="/"> <xsl:apply-templates />, <xsl:template match="text()"> <xsl:value-of select="."/> <xsl:template match="EXISTINGDISEASES"> <xsl:if test="position()=last()”> . <xsl:template match="/"> <TITLE>Patient Information System
3. The solution to the given problem can be achieved using the xmldisplay.htm file. This html file displays a form that contains a text field and a hyperlink. The text field accepts the name of the xml file and clicking on the link invokes a function called cmdsubmit_click. This function is written using JavaScript. This JavaScript function instantiates the DOMDocument.4.0 class and obtains the reference of the object in to a variable xmldoc. Using the load(filename) method of DOMDocument class, the JavaScript function loads the xml file and using the xml property of the DOMDocument class displays the content of the xml file in a message box.
4. You can create an HTML file to display a form that contains a text area and a hyperlink. The text area accepts a string from the . This string is then validated for its conformance as a well-formed xml. The needs to click the submit hyperlink to check it. The onclick event of the hyperlink is processed using a function written in JavaScript. This JavaScript function instantiates the DOMDocument.4.0 class and obtains the reference of the object in to a variable xmldoc. Using the loadxml(string) method of DOMDocument class, the JavaScript function loads the string entered by the . Using the parseError property of the DOMDocument class, the information about any errors in the xml document is retrieved into a variable called error. If there is no error, then the JavaScript function displays the entire string by using the xml property of the DOMDocument, else the JavaScript function displays error.
XML 1u3p2l <meta http-equiv="Content-Type" content="text/html; charset=iso8859-1">
<script Language="javascript"> function cmdSubmit_click() { if (frmPatient.TxtName.value.length==0) { alert ("Invalid XML String"); } else { var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0"); xmldoc.loadXML(frmPatient.TxtName.value); var error=xmldoc.parseError; if(error!="") { alert("error"); } else {
} } 5. To create a text area for accepting XML tags, you need to create a Web page. The Web page displays a form that contains a text area and a hyperlink. The text area accepts a string from the . This string is then validated for its conformance as a well-formed xml. The needs to click the submit hyperlink to check it. The onclick event of the hyperlink is handled using a JavaScript function. This function instantiates the DOMDocument.4.0 class and obtains the reference of the object in to a variable xmldoc. Using the loadxml(string) method of DOMDocument class, the JavaScript function loads the string entered by the . Using the parseError property of the DOMDocument class, the information about any errors in the xml document is retrieved into a variable called error. If there is no error, a new element called “WELLFORMED” is created using the createElement(elementname) of the DOMDocument class. Using the documentElement property of the DOMDocument class, the JavaScript function obtains reference to root element of the xml document into a variable called rootnode. The JavaScript function then invokes the appendChild(elementname) function to attach the node to the root element. Using the text property of a node, the JavaScript function sets the text as good for the WELLFORMED element. The JavaScript function then sets the text of the textarea to the new xml string.
XML 1u3p2l <meta http-equiv="Content-Type" content="text/html; charset=iso8859-1">
<script Language="javascript"> function cmdSubmit_click() { var newelement; var rootnode; if (frmPatient.TxtName.value.length==0) { alert ("Invalid XML String"); 58 eXtensible Markup Language
6. You can create an HTML file to display a form that contains a text area and a hyperlink. The text area accepts a string from the . This string is then validated for its conformance as a well-formed xml. The needs to click the submit hyperlink to check it. The code for creating the HTML page is given below:
XML 1u3p2l <meta http-equiv="Content-Type" content="text/html; charset=iso8859-1">
<script Language="javascript"> function cmdSubmit_click() { var newelement; var rootnode; if (frmPatient.TxtName.value.length==0) { alert ("Invalid XML String"); } else { var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0"); xmldoc.loadXML(frmPatient.TxtName.value); var error=xmldoc.parseError; if(error!="") { alert("error"); } else { rootnode=xmldoc.documentElement; newelement=xmldoc.createElement("WELLFORMED"); rootnode.appendChild(newelement); rootnode.lastChild.text = "good"; frmPatient.TxtName.value=xmldoc.xml } } } function cmdReset_click() { var deleteelements; var rootnode; if (frmPatient.TxtName.value.length==0) { alert ("Invalid XML String"); } else { var xmldoc= new ActiveXObject("Msxml2.DOMDocument.4.0"); xmldoc.loadXML(frmPatient.TxtName.value); var error=xmldoc.parseError; if(error!="") { alert("error"); } else
for (var ctr=0; ctr<deleteelements.length; ctr++) { rootnode.removeChild(deleteelements.item(ctr)); frmPatient.TxtName.value=xmldoc.xml
}
} }
In the above HTML page, the onclick event of the hyperlink is handled by a function written in JavaScript. This function instantiates the DOMDocument.4.0 class and obtains the reference of the object in to a variable xmldoc. Using the loadxml(string) method of DOMDocument class, the JavaScript function loads the string entered by the . Using the parseError property of the DOMDocument class, the information about any errors in the xml document is retrieved into a variable called error. If there is no error then the JavaScript function creates a new element using the createElement(elementname) of the DOMDocument class creates a element named WELLFORMED. Using the documentElement property of the DOMDocument class, the JavaScript function obtains reference to root element of the xml document into a variable called rootnode. The JavaScript function then invokes the appendChild(elementname) function to attach the node to the root element. Using the text property of a node, the JavaScript function sets the text as good for the WELLFORMED element. The JavaScript function then sets the text of the textarea to the new xml string. This html page also provides another hyperlink called Reset. Clicking on this link, gets the list of nodes named WELLFORMED. The JavaScript function uses getElementsbyTagName(elementname) of the DOMDocument class. The JavaScript function then loops through the number of elements returned by the function and uses the removeChild function to remove the nodes. The JavaScript function then sets the text of the textarea to the new xml string. 7. The following XSLT style sheet can be used to display the average student.xsl - This XSLT style sheet uses XPath language to calculate the sum of marks obtained by the student in maths, socialstudies and science and divides it by 3 to get the average marks. Use the html file required to transform xpath/xsl/t syntax.
student.xsl -- >
Maths Total: <xsl:value-of select='sum(//MARKSSUMMARY/STUDENT/TEST/MATHS) div 3'/>
Science Total:<xsl:value-of select='sum(//MARKSSUMMARY/STUDENT/TEST/SCIENCE) div 3'/>
Social Total:<xsl:value-of select='sum(//MARKSSUMMARY/STUDENT/TEST/SOCIALSTUDIES) div 3'/>
student.xml -- >
<MARKSSUMMARY> <STUDENT ID="S001">
<MATHS>90 <SCIENCE>100 <SOCIALSTUDIES>90
<MATHS>80 <SCIENCE>60 <SOCIALSTUDIES>75
<MATHS>70 <SCIENCE>70 <SOCIALSTUDIES>45
8. The languages for defining the structure of an xml document are DTD and XSD. 9. Which of the following is true? a.
Simple Data types contain elements –false
b.
Complex data types contain elements, and attributes – true
10. An object model that allows scripting languages to access and manipulate XML documents is known as Document Object Model.
ADDITIONAL BOOK REFERENCES Erik .T Ray, Learning XML Steven Holzner, Inside XML Elliotte Rusty Harold, W. Scott Means, XML in a Nutshell: A Desktop Quick Reference John Duckett, Professional XML Schemas John Griffin, XML and SQL Server 2000 John Robert Gardner, Zarella .L Rendon, XSLT and XPATH: A Guide to XML Transformations Elliotte Rusty Harold, XML Bible Kurt Cagle, Beginning XML Mark Birbeck, Professional XML Paul .J Burke, Professional SQL Server 200 XML Paul Deitel, The Complete XML Training Course Graeme Malcom, Programming Microsoft SQL Server 2000 with XML Dave Mercer, XML: A Beginner's Guide Michael .J Young, Step by Step XML James Bean, XML Globalization and Best Practices: Using XML Schemas and XML Data