99
XML,WebServices & AJAX i Course Objective: 3. Developing an xml document that acts as textual databases and developing java applications that communicate with xml documc:nts, Use XML to transport the data across different applications In language independent manner(XML) ... . 2. Exposing java based business components (java B ~~~/EJB / Spring beans etc) as services over the web. And writing an 8 application which consumes those services(Webservices) I ! . 3. Developing rich internet applications, which provides asynchronous/fast response without page refresh(AJAX) XML % / i Q.) What is XML? I i I XNlL stands for Extensible Markup Language I I > XML is a markup language much like HTML I " It is also a specification. [ From W3C {World Wide Web Consortium ) ] I I I > XML was designed to describe data. 1 - > XML is self describing. I i- ; Q.) Witat is markup? (Markup = Tagging) I \ -- Enclosing textual content with in textual codes(tags) is nothing but markup. I 8 . I 1 I i Q.) What are the similarities between HTML and XML? i 1 ~3 Both are languages of web. I > Both are markup languages. I I > Both are originated form SGML. [ Standardized General Markup Language(comp1ex) <- GNlL (platform I dependent) ] I > Tags are basic building blocks of both HTNlL and XlML documents. Q.) Is XML is Replacement for HTML? No. Thcir goals are different. .Q.) What are the differences between HTML and XML? ....... ......... HTML . .._:_.,,~_ .- _- ... -. - .. - - -- - -- - .. -- -. -- - -- - . - -. - -- -.- I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 -- I I An IS0 9001 : 2000 Certified Company . . I ..... -...- . - ......... . .- -. -~---....-..---,--p-~p--~--..-. - -- -- -. -- - I Page 1 http://javabynataraj.blogspot.com 1 of 99.

XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

  • Upload
    lamcong

  • View
    217

  • Download
    4

Embed Size (px)

Citation preview

Page 1: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML,WebServices & AJAX

i Course Objective:

3 . Developing an xml document that acts as textual databases and developing java applications that communicate with xml documc:nts, Use XML to transport the data across different applications In language independent manner(XML)

... . 2. Exposing java based business components (java B ~ ~ ~ / E J B / Spring beans etc) as services over the web. And writing an 8 application which consumes those services(Webservices)

I

! . 3 . Developing rich internet applications, which provides asynchronous/fast response without page refresh(AJAX)

X M L %

/

i Q.) What is XML? I

i I XNlL stands for Extensible Markup Language I I > XML is a markup language much like HTML

I " It is also a specification. [ From W3C {World Wide Web Consortium ) ] I I I > XML was designed to describe data. 1 - > XML is self describing.

I i-

; Q.) Witat is markup? (Markup = Tagging) I

\ -- Enclosing textual content with in textual codes(tags) is nothing but markup. I 8 .

I 1 I

i Q.) What are the similarities between HTML and XML? i 1 ~3 Both are languages o f web.

I > Both are markup languages. I

I > Both are originated form SGML. [ Standardized General Markup Language(comp1ex) <- GNlL (platform

I dependent) ] I > Tags are basic building blocks o f both HTNlL and XlML documents.

Q.) Is XML is Replacement for HTML?

No. Thc i r goals are different.

.Q.) What are the differences between HTML and XML?

....... . . . . . . . . .

HTM L

. .._:_.,,~_ .- _- .. . -. - .. - - -- - -- - .. -- -. -- - -- - . - -. - --

-.- I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 -- I I

An IS0 9001 : 2000 Certified Company . . I ..... - . . . - . - ......... . .- -. -~---....-..---,--p-~p--~--..-. - -- -- -. -- - I

Page 1 http://javabynataraj.blogspot.com 1 of 99.

Page 2: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- -- .... . .................-. . --. -

XML Mr.SekharRedd1.z . . . . . . . . . . . . . . . . . . . . ...

I A .....;..:A= =.3

1. Pre defined tags

2. Limited no. of tags -

I 3. Tags are case insensitive

I 4. Tags are meant for displaying the

data but not for describing the data.

1 5. HTML focuses on how data looks

.................. -- .- ?. ;--. -. . - - ........ . . . . . . . .

I Q.) What is the purpose of XML? i

1. User defined tags

2. Tags are extensible

3. Tags are case sensitive

4.Tags are meant for describing the

data

5.) XML focuses on what data is

................

I I 4 XML is used to exchange the information between applications in language (java, .net, PHP) independent,

vendor independent and platform independent manner over web. ! 1 4 XML documents are used as textual databases. I

I 4 XML documents are used as deployment descriptors ... I :, XM L is Used to Create new Internet Languages(XHTML, WSDL, WAP, SNIIL etc) - -

; Q.) What XML Does? !

r-3 Nothing!!! I a Jusl XlVlL was created to structure, store and transport the data.

The following example is a email to SardarG, from Bantha, stored as XML:

....... , .... ... -.-:---c-.-.--->.-.-.e.-===-.r

<errtail? <to>SardarG</t.o> <from>Bantha</from> <suhj ect>Reminder ( P a r t y ) < / s u b j e c t > <body>Donlt f o r g e t me t h i s weekend! </body>

The emall above is quite self descriptive. I t has sender and receiver information, it also has a subject and a message body.

But still, this XML document does not DO anything. I t is just information wrapped in tags. Someone must write a piecec of softwarc to send, receive or display it.

I

Q.) Who invented xml tags? , I

I With XML You Invent Your Own Tags

I The tags in the example above (like <to> and <from>) are not defined in any XML standard. These tags are - "invented" by the author of the XML document. I

I That is because the XML language has no predefined tags.

I The tags used in HTML are predefined. HTML documents can only use tags defined in the HTML standard (like <p>, chi>, etc.). ! -.--A

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 . I I

An ISO 9001 : 2000 Certified Company I ...... - -. .......................................... .... Page 2 -

http://javabynataraj.blogspot.com 2 of 99.

Page 3: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML allows thc author t o define his/her own tags and his/her own document structure. I

; Q . ) What is an X M L document? I

I :) Any text file that is developed with .xml extension is an xrnl document.

Q . ) What is xrnl application?

I 3 Any computer application that works with an xrnl document is nothing but an xrnl application. I 3 Working with XML document means, perform CRUG operations on the XNIL.

XML Syntax

I 1

I An example XML document: I

I

cbody'>Don ' t f o r g e t m e t h i s weekend! </body>

,- the first line in the document: The XML declaration should always be included. It defines the XML version of the document. In this case i the docc~riierit colifor~ns to the 1.0 specification of XML:

i The next line defines the first element of the document (the ro,ot element):

j The next lines defines 4 child elements of the root (to, from, heading, and body):

, < t o > T o v e < / ~ o > ' < f r o ~ n > J a n i < / f rom> ' <headlng,>F.eminder</headlng> I 1 <body>Donl t f o r g e t me t h i s weekend!</body>

I

The last line defines the end of the root element:

All XML elements must have a closing tag

In HTML some elements do not have to have a closing tag. The following code is legal in HTML:

<p>This i s a p a r a g r a p h . . . . . . . . . . . . . . . . . . . . . . . . . . . .

- - -- - -

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

-. -. - .- .- ....... - - - Pai6-3..

An IS0 9001 : 2000 Certified Company - - - .. . .. .... . .

http://javabynataraj.blogspot.com 3 of 99.

Page 4: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

i ;p:"Ti-!j.s i:; another paragraph ! .

/ In XML all elements must have a closing tag like this: I

I <p>Thl-s 1s a paragraph</p> (p>Ti-il s 1:; another paragraph</p>

, XML tags are case sensitive

; XML tags are case sensitive The tag <Letter> IS different from the tag <letter>.

: Opening and closing tags must therefore be written with the same case.

I 1 All XML elements must be properly nested i

I/ I

I ' In HTNlL some elements can be improperly nested within each other like this: I I

i i <b>':l>Th~.s text 1s bold and italic</b></i> 1

i j In XML all elements must be properly nested within each other like ihis

! is text is bold and italic</i></b>

I , ! I

- . I ' . I

All XML documents must have a root tag

All XML documents must contain a single tag pair to define the root element. All other elements must be nested within the root element.: I

All elements can have sub (children) elements. Sub elements must be in pairs and correctly nested within their parent element: I

, I I

<root > <child>

i !

<subchi.ld> I </subchild>! i

! </child>

</root> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

i I

Attribute values must always be quoted

XML elements can have attributes in nameivalue pairs just likein HTML. In XML the attribute value must always be quoted. Study the ; I

two XML documents below. The first one is incorrect, the second is correct: I

. . . . . . . . . . . . . . . . . . . . """ ................... _ "." .. _ ..., _*_ . " .... .i I .

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company ,

- ....... ... . . . . .- . . . .--.-. . .- ,- .. ... - -. - . - - Page 4. ' .

http://javabynataraj.blogspot.com 4 of 99.

Page 5: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

.:~-!f-:i. + 3at.i=i.2/11/99> .- . - . 7'.:l'.2:-2</to>

~:fr~m?Jani</from> i hea : i l ng>Reminde r< /head ing> chodl"Don1t forget me this weekend!</body>

'::/not?;>

.-.::.;nl -,~;+rs.ian="l.O"?>

. :no te date="12/11/99"> ,:.t03.'_Tii~:e<:/to> <f ron'Jani</from> c.:h:+a~-li nt~>Reminder</heading> -body>!?onlt forget me this weekend!</body>

.- .: n c, t 2 ;'

' Entity References

I

Some characters have a special meaning in XML.

' I f you place a character l ~ k e "<" inside an XML element, i t will generate an error because the parser interprets i t as -the start o f a new element. I

-This will generate an XML error:

<rnessage>if salary < 1000 then</message> I

1.0 a v o ~ d t h ~ s error, replace the "<" character with an entity reference:

<messaqe;,if salary &It; 1000 then</message>

, .There are 5 predefined entity references in XML:

- - -- -- - - - -. -- - - - -- - . - -.- - - - - - - Il&lt; 11; -1Fess than

Il I - . . r> Igreater than

. . . . . . . . . I .. -: 1 11' [apostrophe

-- Note: Only the characters "<" and "&" are strictly illegal in XML. The greater than character is legal, but i t is a good habit to replace it.

IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company -- . . - -. ... ............ -.-

Page 5 http://javabynataraj.blogspot.com 5 of 99.

Page 6: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

-. -- .. -- .... ~ -.-.-.-------p.p-

X M I.,

, Comments in XML

' Thc syntax Tor writlng comments in XML is slmllar to that of HTML.

i < ! - - This is a comment - ->

White-space is Preserved in XML

tI-rML trunc:atcs multiple white-space characters to one s~ngle whlte-space:

. . . . . . .~ ...... . . -.-p-p---.p-pp-p-

Tove

... . . . . . . . . . . ......... .. .......

......... -.- .....

I

i With XML, the white-space in a document is not truncated.

I I / Q.) What is a well-formed XML document? I

I > I f an XML document confirms the syntactical rules (above specified) o f XNlL specification is said to be well- . formed. I > An XWlL document is said to be well-formed if it observes the following rules.

I

! 1. I t must begin with the XML declaration

i 2. I t rrlust have one unique root element 3. Start-tags must have matching end-tags

I 4. Elements are case sensitive I 5. All elements must be closed i . .

6. All elements must be properly nested I 7. All attribute values must be quoted I

I 8. Entities must be used for special characters I !

Q.)What is an XML Element? I

An XML clcmcnt is everything from (including) the ele'ment's start tag to (including) the element's end tag. I I

An element can contain:

1. other elements 2. text 3. attributes

... 4. or a mix of all of the above

Q.) What are the XML Naming Rules?

XML clcrncnts must follow these naming rules:

1. Names can contain letters, numbers, and other characters 2. Names cannot start with a number o r punctuation character 3. Names cannot start with the letters xml (or XML, or Xml, etc) I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

An IS0 9001 : 2000 Certified Company ........... ...p-----.-p.--.-.---.....----- pag&-6-.'

I

http://javabynataraj.blogspot.com 6 of 99.

Page 7: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

4. Names cannot contain spaces

Any name can be used, no words are reserved.

, Q;)What are the Best Naming Practices?

1. Make names descriptive. Names with an underscore separator are nice: <first-name>, <last-name>. 2. Narrles should be short and simple, like this: <book-title> not like this: <the-title-of-the-book>. 3 . Avoid "-" characters. I f you name something "first-name," some software may think you want to subtract

name from first. 4.. Avoid "." characters. I f you name something "first.name," some software may think that "name" is a

property of the object "first." 5. Avoid ":" characters. Colons are reserved to be used for something called namespaces.

XM L Attributes I > XML elements can have attributes, just like HTIVIL. I > Attrrbutes provide additional information about an element.

I > Attr~butes can occur in any order in an XML element.

. ~ c , Attribute is unique in an XML element. i.e. It should not be repeated.

example,

<x a--"10" a="20n /> (wrong) - i

XML Attributes Must be Quoted

Attribute values must always be quoted. Either single or double quotes can be used. For a person's jender, the person element can be written like this:

or like this:

. . . - . . . . - . - .-........-......... . . . . . . . . . ~i :person gender= ' female ' >

I .. .............. - -. .- .. - .. - - .-. -. I I f the attribute value itself contains double quotes you can use single quotes, like in this example:

. . . ....... . . . . . .- ....... - .. - .- .- - -

,-<gangster name='George "Shotgun" Zieglerl>

...... 1 . ;... . .- .-. ....... .- . - . . .- .- .......

J r you can use character entities:

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 ! I

An IS0 9001 : 2000 Certified Company . .. . . - -. ..... - ...........-- -. - .... - - -. - -

- l'age-7 http://javabynataraj.blogspot.com 7 of 99.

Page 8: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML

.. , 1 Use of Elements vs. Attributes i I

1-ake a look at these examples:

. . .......... -- .... . . . . . . . . . . . . . . . . .

<person gender-" femalev> - ( 2- .. irst:.n&me>Anna</f irstname>

I I n the flrst example gender is an attribute. I n the last, gender is an element. ~ o t h examples provide the same

I

I lnforrnat~on. I

I I / I 1 There are no rules about when to use attributes or when to use elements. Attributes are handy in HTML. I n XML my --'

I I advice IS to avoid them. Use elements instead. ! I I --I

I i I I ' Avoid using attributes? (I say yes!) I I I I i

I These are some of the problems using attributes:

i attributes cannot contain multiple values (elements can) attributes are not expandable (for future changes)

w attributes cannot describe structures (like ch~ ld elements can) w altributes are more difficult to manipulate by program code

attribute values are not easy t o test against a DTD/XSD

My Favorite Way I I

The following three XML documents contain exactly the same information: 1 A datc attribute is used in the first example:

<to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Donlt forget me this weekend!</body>

</note.> ......................... ..... -, -- . . . . =:

A date element is used in the second example: \ I

I ------- Naresh i Technologies, Opp. Satyarn Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842

An IS0 9001 : 2000 Certified Company I

- - - - - - - -- - - - - -- - - I

Page 8 - http://javabynataraj.blogspot.com 8 of 99.

Page 9: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

,, ;..~ . . . . . . . . . . . . - . ...-.... ~--eL-*-.-----.----

: --.note - ~ <da te>?LO/01/2008</date> , I *:tc2.:To17e<,to>

cfrorn>Gani</from> 1 <heading>Reminder//heading, , I <body>Don'lr forget me this weekend!</body> ' </'n~t?>

.. ~

. ........... . .~ ~

An expanded date element is used in the third: (THIS IS MY FAVORITE): I

- .- . - pp -. .... -- /not 2:. 1 Cdatei

<day>lO</day> i I <month,Ol</month>

.. . ... ,,. ~!;t~,/%008</year> , .,

</date:> 1 <to'Tcve</to> <f r!:ri~',-.Jani</f rom> ,:.!-lt!acJil-rg>Reminder< /heading>

! I tbodyiDon ' t forget me this weekend! </body> i ,I </note:.

. . . . ~ .~ .. . pp -.

I

I

-XML Attributes for Metadata

r-Sometirncs ID references are assigned to elements. These IDS can be used to identify XML elements in much the ! same way as the id attribute in HTML. This example demonstyates this: I

;body>Dontt forget me this weekend!</body>

<note id-"502"> [ I <to>jani</to> <from>Tove</f rom> I <heading>Re : Reminder</heading> <body>I will not</body>

i The id attributes above are for identifying the different notes. It is not a part of the note itself.

/ What I 'm trying to say here is that metadata (data about data) should be stored as attributes, and the data itself should be stored as elements.

r - I '

-XML Documents Form a Tree Structure

i The elements in an XML document form a document tree. All elements can have sub elements (child elements):

.......................... . - -. ..... .... .. -- ..... -.L= ..: i 0 <child> 1 I I . : ............................. ....... - . - -. . - - .- ---

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I ! An IS0 9001 : 2000 Certified Company

http://javabynataraj.blogspot.com 9 of 99.

Page 10: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

The tcrrns parent, child, and sibling are used to describe the relationships between elements. Parent elements have , 1 ch~ldren. Children on the same level are called siblings (brothers or sisters).

I

. , I All elcrncnts can have text content and attributes (just like in HTML).

I Example:

Eler-i~lent: Element:

Siblings

Root element: .:::b~:~okstore,:.

I

Text :

~ a r e t - ~ t ]

i

The imagc above represents one book in the XML below: i

I I ....... . . . . . . . . . . . . - ........ - .- -. - ---.7 . --- -- - -- - -. .. -- ..... . . . . .

- I .- . . . . . . . . . . . . . . . . . . . . .. ........ -- -- -- - - - -. ' <bookstore> b

. . . <book category="COOKING">

<title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author>

:I I <year>2005</year> I <price>30.00</price> I i

</book> <book category="CHILDREN">

<title lang="enW>Harry Potter</title> , I I

iauthor>J K. Rowlii~g</author> <year>2005</year> <price>29.99</price>

I I </book> <book category="WEBW>

Y I ' <title lang="en">Learning XML</title>

<autkor>Erik T. Ray</author> - 1 1 <year>2003</year> <price>39.95</price>

</book> I i

1 Child

---- I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- - - - - - - . . - - . - - - . - -- - - -- An IS0 9001 : 2000 Certified Company

-- 1

p a g e i n - -

Element: <~I:IQ~>

http://javabynataraj.blogspot.com 10 of 99.

Page 11: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Q.) How to view XML files?

I 1 3 [3y using Browsers, text editors, XML editors we can view XNlL files.

I Q.) How to develop an XML document?

a In order to develop a useful xml document, we need to develop one more file. 1.e. DTD or XSD file.

I a In DTD file or XSD file we specify the XML vocabulary.

I Q.) What is a valid XML?

I a If an XML document is developed according to rules

specified in DTD / XSD, it is known as valid XML document. I

1 NOTE: Every valid XML is a well-formed, but vice versa .need not be true.

! ; [First well-formedness is checked then it checks for validness will be checked]

I i Q.) How to check the well-formedness of XML document? i i I a Using XML parsers, XML Editors, Browsers .... etc.

I

Q.) How to validate XML document? -

- r,> Using XlVlL parsers, XlVlL editors ... etc.

Every XML application needs two things to work with XML

1. Parser

2. API

Q.) What is an XML parser? What are its functions?

10 XML parser is an API that enables XML applications to work with XML document.

I- > An XML parser performs the following things. 1. read in^ the XFAL document. 2. Checking well-formedness

. 3. Verify its validity. 4. Making XML data available to XML application.

Naresh .~echnolo~ ies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- - - - - - . . - - - . An IS0 9001 : 2000 Certified Company

~aC-1 i- -- http://javabynataraj.blogspot.com 11 of 99.

Page 12: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

I I I 1. XNII. application instantiating the parser and specifying the

I XML file to the parser. (i.e. Passing the name of the XML file name t o the Parser )

I 2. Parser reads the specified XML document and verifies its well-formedness.

I 3. In the XML document parser gets the information about the D'TD or XSD. I I'arser verifies the correctness of the DTD or XSD. I 4. Parser reads the metadata specified in the DTD or XSD file into the memory. 1 5. Basing on the metadata read into memory; XML Parser verifies the validity

of the XNlL document. 6. Parser makes XML content (data) available t o the XML application either in

the form of a tree structure or in the form of events.

{The way DOM makes available data to the XML application is differ from JAXB }

Valid XML document

1 3 XML parser can make data stored in XML document available to XML application if and only i f f the XML documents are valid.

I 3 There are two approaches for developing valid XML. o Using DTD o Using XSD

Q.)What is DTD?

1 3 DTD stands for Document Type Definition.

I > A DTD is a text file with .dtd extension.

13 I f XML file holds data, its corresponding DTD holds Meta data.

I > In a DTD legal building blocks of an XML documents are specified.

1.e. XML vocabulary is specified in a DTD.

Q.) What are the constituents of DTD file? (Contains) I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I An IS0 9001 : 2000 Certified Company I

- . . -- - - . . - -. -- -. -- Page 1 2 -

http://javabynataraj.blogspot.com 12 of 99.

Page 13: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- - - - -- -- - - - - - - -- -- - - - - - - -- .- -- --

From a 111 0 p o ~ n t of vrew, all XML documents are made up by the follow~ng b u ~ l d ~ n g blocks:

I Elements ALLrrbutes E n t ~ t ~ e s PCDATA

I CDATA

I Elements i

1 Elemcnts are the main building blocks of both XlYL and HTML documents. I

I

Examplcs of HTML elements are "body" and "table". Examples of XML elements could be "note" and "message". I I I Elcmerits can contain text, other elements, or be empty. Examples of empty HTML elements are "hr", "br" and "img". i I

) Examples: I

-4ttributcs provide extra information about elements.

4ttributcs are always placed inside the opening tag of an element. Attributes always come in name/value pairs. The following "irng" element has additional information about a source file:

The name of the element is "irng". The name of the attribute is "src". The value of the attribute is "computer.gif". Since the element itself is empty i t is closed by a " /".

Entities

Some characters have a special meaning in XML, like the less than sign (c) that defines the start of an XVIL tag.

Most of you know the HTML entity: "&nbsp;". This "no'-breaking-space" entity is used in HTML to insert an extra space in a document. Entities are expanded when a document is parsed by an XML parser.

'The following entities are predefined in XML:

Entity References Character

NJ resh i Technologies, Opp. sat yam Theatre, Ameerpet, Hydera bad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

.. . . .~. . . . . . . .-

Page i3- http://javabynataraj.blogspot.com 13 of 99.

Page 14: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

-.... .-.. . . . . .................... . . . . . . . . . . . ,

X M L Mr.Sel<harReddy -

I

PCDATA - Parsed Character Data I

XML parscrs normally parse all the text in an XML document.

When an XML element is parsed, the text between the XML tags is also parsed

I The parser does this because XYlL elements can contain other elements, as in this example, where the <name>

/ element conta~ns two other elements (first and last):

I - - - - -

<name><f~rst>B~ll</flrst><last>Gates</last></nam~>

- - -. - - - - -- .- - .... - .....-. - . - -

and the parser w ~ l l break i t up into sub-elements like this:

Parsed Character Data (PCDATA) is a term used about text data that will be parsed by the XYIL parser.

CDATA - (Unparsed) Character Data

The tcrrn CDATA is used about text data that should not be parsed by the XML parser.

Characters like "<" and "&" are illegal in XML elements. -

"<" will generate an error because the parser interprets it as the start of a new element.

"&" will generate an error because the parser interprets i t as the.start of an character entity.

.Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as ; CDATA. I Everythi.ng inside a CDATA section is ignored by the parser.

I A CDATA section starts with "<![CDATA[" and ends with "]I>":

I

. ..................... . . . . . . . . . . . . . I

I <script > 2 1 /

< ! [CDATA[ ...... - - ..-........ -. , - . - - -. . - . - - - - . ........... ... --.---" i

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company 1 --- I.

- . ...........--........ - Page 147 -

http://javabynataraj.blogspot.com 14 of 99.

Page 15: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. . - . . . . . , .. . . . , /I - . . - - - . .. .. . -.

- r ~ l n . : r i r ) r : !::atchwo (a, b\

then

I

I n the cxamplc abcve, everything lnslde the CDATA sect~on IS ~gnored by the parser.

' Notes on CDATA sections:

' A CDAl A scction cannot contain the string "]I>". Nested CDATA sections are not allowed.

I The " ] ]>" that marks the end of the CDATA section cannot contain spaces or line breaks. I

--

I DTD - Elements 1

1TDeclaring an Element I l~ I\ In the DTU, XML elements are declared with an element declaration. An element declaration has the following syntax: I

< ! ELEMENT element-name (element-content ) > I I

I '

1 Empty elements 1 %

Enipty elements are declared with the keyword EMPTY inside the parentheses:

< ! ELEMENT element -name (EMPTY) >

example : : ! ELEYIENT br (EMPTY) >

Elements with data

Elements with data are declared with the data type inside parentheses: . -

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- . . . - - - - - - . -. An IS0 9001 : 2000 Certified Company --

--

Page IS - http://javabynataraj.blogspot.com 15 of 99.

Page 16: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. . . ~~ ~ ....-. ~ ... ~ -L-p----p-----.-p-p ~ ~ .--- ~-

XML ~ r . ~ e l < h a r ~ e d clij-:

; -: i ELEt.!!.<biT element-name (#CDATA) > C r

I

! .:: ! ELE'4ENT slement-name (#PCDATA) > . , 0 1 - ! : c: ! ELEMENT element-name (ANY) > j e:.;ample: 1 *::! ZLEI.1kT,?1T note (#PCDATA) >

. . .

I # c ~ ~ ~ A ' r n e a n s the element contains character data that is not supposed to be parsed by a parser i I #PCDATH mearis that the element contains data that IS going to be parsed by a parser.

The keyword ANY declares an element with any content.

I If a #PCDATA sectlon contains elements, these elements must also be declared. I

Elerner~ts with children (sequences) . I

/ Elemerits w~ lh one or more children are defined with the name of the children elements inside the parentheses: I I I

<!ELEMENT element-name (child-element-name)> 1 or '. . i <: i ELEPIENT element-name (child-elenent-name, child-element-name, . . . . . ) example : i

\ 8

! _I

I

When children are declared in a sequence separated by commas, the children must appear in the same sequence in the document. In i a full declaration, Lhe children must also be declared, and the children can also have children. The full declaration-of the note documentl_i will be: I

< ! ELEMENrI' note (to, from, heading, body) > K ! EL.EIiE;l? t r 3 (#CDATA) > < ! ELEMENT from (BCDATA) > < ! ELEMENT heading (#CDATA) > <!ELEMENT body (#CDATA) >

- : Q.) What is cardinality operator in DTD? I

I 3 An XML element can occur zero or more times in the XML document. 1 - Cardinality operator specifies the no. of times an XML element

can occur in XNlL document. I In a DTD we have three cardinality operators.

o ? (0 or 1) o -t (1 or n) o * (Oorn)

Note: If a cardinality operator is not associated with the XML element, that element should occur exactly once in the XML document.

Declaring only one occurrence of the same element

<!ELEMENT element-name (child-name)>; . " . ,.,,,.".",%,--"----~-,.-.------.-,..--"--.-.."..-"-,."*.-"."..,--..A< ~ ~ 1 -- -

-- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company 1

- Page 16

http://javabynataraj.blogspot.com 16 of 99.

Page 17: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. .. . . - - - . - - . - - - -- - - -- - . . -- - -- - -- - - -- -- - -. - .- . - - - - -- - . - - - - - - -- - - . - - . . - - -- -. -. . .

X M L ~ r . ~ e k h a r ~ e d c l ~ i

2xa1nple

-1 ! ELEMELJT note (message) >

The example declaration above declares that the child element message can only occur one time inside the note element.

Declaring minimum one occurrence of the same element

. ' ! ELEMENT element-name (child-narnsa) > zxample ( ! EL,EMEN'T note (message+) >

I

The + sign ir i the example above declares that the ch~ld element message must occur one or more times inside the note element I

~ I

Declaring zero or more occurrences of the same element

< 1 ELEMENT element -name (child-name* ) > er.an;pl e < 1 ELEMENT note (message*) >

The * sign in the example above declares that the child element message can occur zero or more times inside the note element.

-declaring zero or one occurrences of the same element

: ! ELEMENT element--name (child-name?) > example < ! ZLE,PENT cote (message?) >

The ? sign In the example above declares that the child element message can occur zero or one times inside the note element.

Declaring mixed content . .

The example above declares that the element note must contain at least one to child element, exactly one from child element, exactly ~ n e header, zero or more message, and some other parsed character dataas well.

DTD - Attributes

- geclaring Attributes

In the DTD, XML element attributes are declared with an ATTLIST declaration. An attribute declaration has the following syntax:

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

A n IS0 9001 : 2000 Certified Company

http://javabynataraj.blogspot.com 17 of 99.

Page 18: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- - -- --- - - - - - ---- --. - - - --

XML ~ r . ~ e k h a r ~ e d d v

As you can see from the syntax above, the ATTLIST declaration defines the element which can have the attribute, the name of the attribute, the type of the attribute, and the default attribute value - 1 - 1

The attribute-type can have the following values:

Value Explanation

- P - l 7

L -L!-. The value 1s character data

!evallevail..) The value must be an enumerated value

ID The value is an unique ld

i CKZ r' The value is the id of another element

T DREFS The value is a llst of other ids

t\!P4TOKEN The value is a valid XML name

NLvIT~KE[\IS The value is a list of valid XML names

, ENTITY The value is an entity

ENTITIES The value is a list of enti

MOTATlON e value 1s a name of a no

xml :

The attribute-default-value can have the following values:

Value Explanation

#IMPLIED optional attribute

#FIXED value The attribute value is fixed

Attribute declaration example DT'D example: <!ELEMENT square EMPTY> I

< ! ATTLIST square width CDATA "O">!

XML example: <square width="lOO"></square>

In the above example the element square is defined to be an empty element with the attributes width of type CDATA. The width ,attribute has a default value of 0.

Default attribute value Syntax : <!ATTLIST element-name attribute-name CDATA "default-value"

DTD example : <!ATTLIST payment type CDATA "check1'>

I I

--- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- -- -- - - An I S 0 9001 : 2000 Certified Company _I

Page 18 - http://javabynataraj.blogspot.com 18 of 99.

Page 19: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Specifying a default value for an attribute, assures that the attribute will get a value even if the author of the XML document didn't ;nclude it.

, Implied attribute !

Syntax: i <!HTTLIST element-name attribute-name attribute-type #IMPLIED> 1 ITD examp12 : .:iATTLTST contact Fax CDATA #IPlPLIED> I

! .Valid XML:

I <contact fax="555-667788" / > 1 I

Valid XC.:lL: I I i , <contact. /> i

! i 1

. . Use an llnplied attribute if you don't want to force the author to include an attribute and you don't have an option for a default value I either. I ,

i ( Required attribute I I 1 Syr~tar::

<!ATTLIST element-name attribute - name attribute-type #REQUIRED> I DTD exan~pl?:

! AT'TLIST person number CDATA #REQUIRED> t I I XML example: ,-<person nuntber="5677"> I

I Invalid XML:

1 <person / > I

, Use a required attribute if you don't have an option for a default value, but st111 want to force the attribute to be present. 1 I 1 Fixed attributevalue I Syntax:

I <!ATTLIST element-name attribute-name attribute-type #FIXED "valuev>

1 DTD example:

,I <!ATTLIST sender company CDATA #FIXED "Microsoft">

I XML example:

/ <sender company="Microsoft"> I Invalid XML:

I Use a flxed attribute value when you want an attribute to have a fixed value without allowing the author to change it. If an author I includes another value, the XML parser will return an error.

- -

! - - - 1 I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I -- -- An IS0 9001 : 2000 Certified Company Page IT-'

http://javabynataraj.blogspot.com 19 of 99.

Page 20: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Enumerated attribute values , - , I

Syntax : - I

<!ATTLIST element-name attrlbute-name (evallevall . . ) default-value> _ i ! I

DTD example: <!4TTLIST payment type (checklcash) "cashw>

XML example : I <payment type="checkW> j or : .<payment type="cashn> i i .

( Use enumerated attribute values when you want the attribute values to be one of a fixed set of legal values I

1 Element with multiple attributes I

I <!ATTLIST book 11 publication CDATA "sekahr l1 pages CDATA #FIXED "150" color CDATA #IMPLIED lsbn I D #REQUIRED I

1 DTD - Entities

I Entities Entities as variables used to define shortcuts to common text. Entity references are references to entities. Entities can be declared internal. Entities can be declared external

I Internal Entity Declaration Syntax': <!ENTITY entity-name "entity-value1'>

I

DTD Example: <!ENTITY writer "Jan Egil Refsnes. "> <!ENTITY copyright "Copyright XML1O1.I1

External Entity Declaration Syntax: <!ENTITY entity-name SYSTEM "URI/URLW>

--- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L - ..-: - -- An Iso 9001 : 2000 Certified Company i

J Page 2(.

http://javabynataraj.blogspot.com 20 of 99.

Page 21: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. ~ ~ ~ - - --...A- .. - .-

. YML Mr.SekharReddy ; I

- ATD Example: <!ENTITY writer SYSTEM "http://www.xm~lOl.com/entities/entities.xml">~

' ! EPITI'T'L' copyright SYSTEM "http: //www. xmllol. com/entities/entities. dtdr'>'

YML exsmple: .authcr>&wr~ter;icopyright;</author>

Q.) How to associate a DTD with xml? I

I > We need to specify DOCTYPE declaration after XML declaration, in order to associate a DTD with the X M L document.

I > A DTD can be declared o Inside an XML document o External reference.

Internal DTD Declaration I I

.f the DTD is declared ins~de the XML file, i t should be wrapped in a DOCTYPE definition with the following syntax:

- ---. -- P P

11 < ! DOCTYPC root -element [~lement-declarationsp -

I Example XML document with an internal DTD:

! -- . - - - - .- - --- -- - - . - -- . , . . .. . -. . .~ -- - -. .. . . - . .- - . . .

<?xml version="l.O"?> <!DOCTYFE note [ < ! ELEMENT note (to, from, heading, body) > <!ELEMENT to (#PCDATA) >

< ! ELEMENT heading (#PCDATA) > < ! ELEMENT body ( # PCDATA) >

<note> <to>Tove</to> <frorn>Jani</from> <heading>Reminder</heading> <body>Don1t forget me thls weekend</body> 1 [I </nore> - -. -- --- -

I The DTD above is interpreted like this:

!DOCTYPE note defines that the root element of this document is note . !ELEMENT note defines that the note element contains four elements: "to,from,heading,body.'

!ELEMENT to defines the to element to be of type "#PCDATA" ! !ELEMENT from defines the from element to be of ~ ~ ~ ~ ' " # P c D A T A ' ' 0 !ELEMENT heading defines the heading element to be of type "#PCDATAn

I !ELEMENT body defines the body element to be of type "#PCDATAVt

I ---.- -

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,-23734842 I -- - -

An IS0 9001 : 2000 Certified Company - ~a~e'23-

http://javabynataraj.blogspot.com 21 of 99.

Page 22: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

External DTD Declaration

I f the DTD is declared in an external f~le, i t should be wrapped in a DOCTYPE definition with the following syntax: 1

<lPQCT' iPI I root-element SYSTEM "filename and location">

- - .up - -.-----A- -

1 This is thc same XML document as above, but with an external DTD

..... . . . ...... ....

<?xml cersion="l.O"?> < ! DOCT-YPE note SYSTEM "note. dtdl'>

. <heading>Reninder</h?ading> <body>Don't forget me this weekend!</body>

</note> . . . . . . . . . . . . . . . . . . .

And this is the file "note.dtdU which contains the DTD:

. ~ .. . .- -- . . . . . -. ..... -- < ! E L E M E ~ T T note < ! ELEMENT to ( # PCDATA) > < ! ELEMENT from (#PCDATA) > < ! ELEMENT heading (#PCDATA) > < ! ELEMENT body ( # PCDATA) >

........... ..........

Note: Internal DTD's are seldom used. Reusability o f DTD's across XML documents is not possible wi th internal DTD. I I I

Q.) Develop a DTD file for the following XML file? ,- 1 . , - I Message.xml

! I i

<message> <to>ram</to> <from>sam</from> <body>hi, how are you</body>

</message> messape.dtd

<! ELEMENT message (to, from, body)> <! ELEMENT t o (#PCDATA)> <! ELEMENT from (#PCDATA)> <! ELEMENT body (#PCDATA)>

Q;) Develop an external DTD for the following XML document?.

I ----- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 /

I I. _ . _. _ _ __ - An IS0 9001 : 2000 Certified Company

p a g e T - '- http://javabynataraj.blogspot.com 22 of 99.

Page 23: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

<!DOCTYPE students SYSTEM "student.dtdV > '

<students> <student regno="nit001" >

<name>david</name> <coursehXNI L</course> <fees-status>NotYet</fees-status> <working>yes</working>

I / student.dtd

I <!ELEMENT students(student+) >

I <!ELEMENT student(name, course, fees-status, working?) >

I <!ELEMENT name (#PCDATA) >

i <!ELEMENT course (PCDATA) > - I <!ELEMENT fees-status (PCDATA) >

<!ELEMENT working (#PCDATA) > 1

,- <!ATTLIST student ID #REQUIRED > I

1 . items.xml

I <?xml version="l.O" ?> <!DOCTYPE items SYSTEM "items.dtdU>

1 items.dtd <?xml version="l.O" encoding="UTF-8"?>

1 <!ELEMENT items (item+) > <!ELEMENT item (price) >

I <!ELEMENTprice(#PCDATA)> -

< !ATKIST item code ID #REQUIRED >

boo kstore.dtd

I . <!ELEMENT bookstore(name, topic+)> <!ELEMENT name (#PCDATA)>

1 <!ELEMENT topic(topic-name, book+)> -- .-.-- - .- - - --

I .

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

Page 23 http://javabynataraj.blogspot.com 23 of 99.

Page 24: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

<!ELEMENT topic-name (#PCDATA)> <!ELEMENT book(title, author) > <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ATTLIST book isbn ID #REQUIRED >

bookstore.xmI , <?xmI version="l.O" ?> 1 <!DOCTYPE bookstore SYSTEM "bookstore.dtd">

< booltstore > I <name>HydBookStore</name>

<topic> <topic-name>XML</topic-name> <book isbn="b12345" color="red"

pages="150" publication="sekhar" > <title>lVlikels Guide to DTD's and XML Schemas</title> I

I <author>Mike Jervis</author> <price>68.0</price>

</book> <book isbn="b12346"> ~ * <title>XSD in 24 hours</title>

1 I <author>David</author> i </book> I </topic> / </ bookslore >

i ! , Q.) What is a prolog in an XML file or in an XML document? I

I > An XML document is divided into two parts. I I o Prolog i o Body 1

1 . 1 I > Root element is nothing but the body of the XML document.

- Prolog is that part o f the XML document which comes before the root element. 1 3 Generally prolog contains XML declaration and DOCTYPE declaration.

I

i Q.) What do you know about SYSTEM keyword in DOCTYPE declaration?

I 3 SYSTEM keyword indicates that the specified DTD is a private one. Almost always we use this (SYSTEM) keyword I only in DOCTYPE declaration.

3 Another keyword i.e. an alternative for SYSTEM is PUBLIC.

Example:

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//ENn "h_tLp;/'a-va.sun.com/i2ee/dtds/web-ap~ 2 2.dtdW>

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- - - . . - - - . . .- . -- - - - - - An IS0 9001 : 2000 certified Company

-- Page 2:'

-- http://javabynataraj.blogspot.com 24 of 99.

Page 25: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- .

+ - Standardized body

- = Not Standardized body

' W3C = Organization Name

Hibernate = Name of the DTD

Version 1.0 - Version name

EN = Language

Q.) What are the limitations of DTD?

1. Wealter data types. I -

,, 2. Constraints can't be effectively specified. 8 , 3. Ooesn't follow XML syntax, and hence not productive. I I

I\

XML schemas

I I '

Q.) What is an XSD?

1 , XSD Stands for XML Schema Definition I , An XML schema is used t o define the structure of an XML document.

I i

I :, Schemas are successors t o DTDs. , I

I Schemas are another approach used by the XML parser to validate an XML document. I I It is a text file with .xsd extension. j I Q.) What XSD defines? I

I . I3efines elements that can appear in a document 1 2. Defines attributes that can appear in a document

3. Defines the iluinber of child elements and their sequence i 4. Ilefines whether an element is empty or can include text

5 . Detines data types for elements and attributes 1 6. Defiiles default and fired values for elements and attributes

Q.) Compare and contrast DTDs and XSDs? i I

. - -- Page 2 5 -

i I - .-

. . ---- 1

i Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 An IS0 9001 : 2000 Certified Company

--

DTDs XSDs

http://javabynataraj.blogspot.com 25 of 99.

Page 26: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. .~ . .

XML ~

Wn2,*?4Cif :**,<, ~ , . , + ~ M ~ ~ r s

. . ~ .pp-.-ppp--

1 1. Used for legacy XML documents I

I 1. Used for current XML documents

1 2. Follows EBNF(Extensible Backup Norm 1 2 Follows XML syntax.

1 Form) syntax.

3. Limited data types. So not type safe.

4. Cardinality control over the elements is

limited

5. Cannot define our own data types

6. Doesn't support namespaces

3. Rich in data types, So it is type safe.

4.Provides much more cardinality

constraints

5. Can define our won data types.

6. Supports namespaces

I Data Types I

I Onc of the greatest strength of XML Schemas is the support for data types . An XSD comprises of two kinds o f data 1 types. I

I -I

1. Simple Types 2. Complex Types 1

- 1 I

Schema Elements

I -- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

An IS0 9001 : 2000 Certified company Page 2f --

http://javabynataraj.blogspot.com 26 of 99.

Page 27: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Q.) What is a Simple Element?

simplc clcmcnt is an XML element that can contain only text. But is shouldn't contaln any sub elements or attr~butes.

I

Element

1 XML Schema specifies 44 built-in types, I

I I 9 of which are primitive. i

String, Boolean, decimal, float, double, duration, dateTimel time, date, gYearMonth, gYear, g~onthDay, gDay, gMonth, / hexBinary, base64Binat-y, anyURI, QName, NOTATION

/ 25 of which Built-in Derived Data Types normalizedstring, token, language, NMTOKEN, NMTOKENS, Name, NCName, ID, IDREF, IDREFS, ENTITY, ENTITIES, / integer, nonPositivelnteger, negativelnteger, long, int, short, byte, nonNegativelnteger, unsignedlong, unsignedlnt,

I unsignedshort, unsignedByte, positivelnteger. I 1

/ ,The most common types are -~ -

I 1. xs:string 2 , xs:decimal 3. xs:integer 4. xs: boolean 5. xs:datc 1 6. xs:time

--

1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, ~ h : 040-23746666, 23734842

. - - - - - . . . - - -. -. An I S 0 9001 : 2000 Certified Company ,

p a g e r http://javabynataraj.blogspot.com 27 of 99.

Page 28: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Defining a Simple Element

Syntax:

where element-name is the name of the element and element-type is the data type of the element.

Q.) What is the XSD equivalent for the following'XML element?

XML elerncr~ts:

XSD def~nition:

/ Q.) How to give Default and Fixed Values to Simple Elements 7 i

/ "color" clement default value is "red": i

1 "color" clcment fixed value is "yellow": I

>

j

1

- -- -- i 1 <xs: element name="colorfl type="xs:string" fixed="yellow"/> I - -- -- . . --- - - - - -- - I

........-. - . -- -- . . - . . - ..-A

. <xs : element name="colorff type="xs : string" default="redW/>

I I Q.) How to Define an Attribute? I

I .: . . . . . . . . - - -. - - -.

i

Syntax:

..... . . . . . ... . . . . . . . . . . . . . .

I -. - - - - --

<xs : at tribute name="attribute-name" t ype=llattribu'te-type1'/>

- .~ . . . . . . . . . - . - - ... ...-. -. . .-

1 Wherc attribute-name is the name of the attribute and attribute-type specifies the data type of the attribute. I I

----- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I

1 - - -- . - - -- -- _ - An I S 0 9001 : 2000 Certified Company

Page 2.' - - http://javabynataraj.blogspot.com 28 of 99.

Page 29: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

4.) What is the XSD equivalent for the following XML element?

ML element:

. . . .......... .. . ....... $ . - - - .- -- - - - .- - - - --

<las t r i ame lang="EM">Smit?i</lastname>

. - .. A -- -- -

XSD definition:

:xs: a t t r i b u t e name="langl ' t y p e = " x s : s t r i n g u / > ( <ns : e1.amrnt namr="las tname" typo="xs : s t r i n g " /> I

1 1 Q.) How to define fixed and default values to attributes?

I 1 Fixed Values for Attributes

!. ; -~efau' l t Values for Attributes I . -. . - -- - - -. -. . . . . . . , .......

i 1 < X S : a t t r i b u t e name="lang" t ype=Ifns: s t r i n g " de fau l t="EN" />

, ....................... ...... ....

j

I Q.)How to specify an attribute as optional/ required?

Optional Attributes

. . . . .......... . . .

I 1 c x s : a t t r i b u t e name="langl ' t ype="xs : s t r i n g "

/ 11 . . . . .

I

NOTE: By default an attribute is optional attribute

-. - Required Attributes

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- -. An IS0 9001 : 2000 Certified Company

Page 29 http://javabynataraj.blogspot.com 29 of 99.

Page 30: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XSD Restrictions/Facets I

I I !

I Restr~ct ions are used t o define acceptable values for XML elements or attr ibutes. Restrictions on XPIL , e lements are called facets.

I

-, i I

Restrictions on Values

, The fol low~ng example defines an element called "age" with a restriction. grcalcr than 30:

... - ... . .. .........

<xs : clement name="age"> <-,- .,., - . . . :; i.mpl.eType>

.( .,,:restriction . . =- base="xs:integerW> <xs:minInclusive value="18"/> ~xs:maxInclusive value="3OU/>

<!xs: restriction> </xs:simpleType>

</ss:element> ~ -~ ........

I I

1 The value of age cannot be lower than 18 or ,

Restrictions on a Set of Values

To l ~ m i t the content of an XML element to a set of acceptable values, we would use the enumeration constra~nt. h i I

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:stringW> I <xs:enumeration value="AudiN/>

The example above could also have been written like this: I

1

<xs:simpleType name="carTypel'> <xs:restriction base="xs:string">

<xs:enumeration value="Audi"i> <xs:enumeration value="Golf"/> <xs: enumeration value="BMW1'/>

'</xs: restriction> </xs : si~npleType>

............. ,. -- .............

I I

I Note: I n t h ~ s case the type "carType" can be used by other elements because i t is not a part of the "car" element.

I --- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L - - - . - - - . - --- An IS0 9001 : 2000 Certified Company Page 3- -

http://javabynataraj.blogspot.com 30 of 99.

Page 31: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Restrictions on a Series of Values

,,attcrr~ corlstraint can be used t o l imit the content of an XML elernmt to define a series of numbers or letters

ixample#l Acceptable value is ONE of the LOWERCASE letters from a to z:

I- :xs: eletnent name="letterU> <xs : simpleType>

I <xs : restriction base="xs: stringrf> <xs :pattern value=" [a-z] " / > 1 </AS: restriction,

/ ., iy:-. .,., . simpleType>

1 Exarnple#Z Acceptable value is THREE of the UPPERCASI i l .

<XS : element name="initialsff> <xs: simpleType>

i.;lr ixs:restriction base="xs:stringVi <xs :pattern value=" [A-Z] [A-Z] [A-Z] 11/>

r </xs:restriction> </ss: simpleType>

I. .</xs :element> 1-

letters from a t o z:

( Example#3 Acceptable value is THREE of the LOWERCASE OR UPPERCASE letters from a to z: i

<xs:elzment name="inltials"> 1 < r s : slmpleType> <xs : restriction base="xs : stringf1> <xs:pattern value="[a-zA-Z] [a-zA-Z] [a-zA-Z]If/>

':/xs: restriction> 1 11 </as : s~mpleType>

</xs :element>

I Example#4 Acceptable value is ONE of the following letters: x, y, OR 2:

- -

1 Exarnple#5 Acceptable value is FIVE digits in a sequence, and each digi t must be.in a range from 0 to 9:

It<xs:elernent name="choice">

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 An IS0 9001 : 2000 Certified Company

I I

- .- - - - - . .

Page 3T --

<xs : simpleType> <ns:restriction base="xs:string"> <ss:pattern value=" [xyz] " />

</xs:restriction> </xs:simpleType>

</xs : element>

http://javabynataraj.blogspot.com 31 of 99.

Page 32: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. -. . .- ----- -. -- - - - - -- - - -

XML Mr.SekharReddv -.,I

.-:xs :pattern value=" [O-91 [O-9) [O-91 [O-91 [O-9) ' I / >

,,r ! y s : restrict ion> </xs:simpleType>

<,,'>:s : s?ernent>

Example#6 Acceptable value is zero or more occurrences of lowercase letters from a to z: i

i <>:s: el s~nent name="letter">

<xs : s impleType> .-. ..., . :;:restriction base="xs: stringu>

I' x.. P .pattern . value=" ( [a-z] ) * " / > ,</:,:s: restriction>

</xs: sirnpleType> </xs :element>

Exarnple#7 Acceptable value is one or more pairs of letters, each pair consisting of a lower case letter followed by an I uppcr case letter. For example, "STOP" will be validated by this pattern, but not "Stop" or "STOP" or "stop": I

I

<xs: element narne="letterV'> <:,:s : s impleType>

. <xs :restriction base="xs: string1'> <:xs :pattern value=" ( [a-z] [A-Z] ) +Ir/>,

. : i : xs :restriction> </xs : simpleType>

.</xs :element>

Example#8 Acceptable value is male OR female:

/

Exarnple#9 There must be exactly eight characters in a row and those characters must be lowercase or uppercase letters from a to z, or a number from 0 t o 9:

<xs : element name="passwordl'> <xs : s impleType>

<xs:restriction base="xs:string"> <xs :pattern value=" [a-zA-ZO-91 {8} " />

</xs:restriction> </ss:simpleType>

</xs :element>

Example# 10 : Element to restrict the Password simple type to consist of between six and twelve characters, which can only be lowercase and uppercase letters and underscores

I I

I <

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

L-- - - - - - An IS0 9001 : 2000 Certified Company

Page 3 2 - I

http://javabynataraj.blogspot.com 32 of 99.

Page 33: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

sium bet^ of Digits i

Using ::.i:i:sLi',l.y.it~ and f r a c t i o n U i q i -s, we can further specify that the Szlar:; type should consist of seven digits, two of which come after the decimal point. Both tota.1.D:~.(~~i.:ts and fracti.,onDi,.g.i.t:s are I

j

rnaxi;iit.rn;s. That is, if totaLDigits is specified as 5 and 5ractionDigits is specified as 2 ! a valid I

number could have no more than five digits total and no more than two digits after the decimal point.

i : , . Restrictions on Whitespace Characters 1 I '

To specify how whitespace characters should be handled, we would use the whitespace constraint. ! I ' This example defines an element called "address" with a restriction. The whitespace constraint is set to I i "preserve", which means that the XML processor WILL NOT remove any white space characters: i i i

<xs: s imp1 eType>

111 <xs : rcstri ction base-"xs : stringf'> <xs:whiteSpace value="preserveff/>

i 9 replace - all tabs, line feeds, and carriage returns $e replaced by single spaces. I collapse - all tabs, line feeds, and carriage returns are replaced by single spaces and then all

i groups of single spaces are replaced w~th one single space. All leading and trailing spaces are

- - then removed (i.e, trimmed).

I Restrictions on Length

1 TO lirnil the length of a value in an element, we would use the length, maxlength, and minLength constraints.

1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 ... - -..---.-.pp

An I S 0 9001 : 2000 Certified Company -

Page 33-- http://javabynataraj.blogspot.com 33 of 99.

Page 34: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

This example def~nes an element called "password" wi th a restriction. The value must be exactly eight characlers: --

I I

i Restrictions for Datatypes (-1

‘This example def~nes another element called "password" with a restriction. The value must be min imum five characters and maximum eight characters:

I

I I I I 1 Constraint Description i I ,

I i I I i i

I

I Enumcrat~on Deflnes a list of acceptable values i i

1 I

i 1

( frdctlorlD~g~ts Specifies the maximum number of decimal places allowed. Must be equal to or greater 1 than zero i I

I ; I 1 Lcngth Specifies the exact number of characters or list items allowed. Must be equal to or

greater than zero I < I - 1

( maxExclustvc Specifies the upper bounds for numeric values (the value must be less than this value) I I ' I / rnaxl nclus~vc Specifies the upper bounds for numeric values (the value must be leis than or equal to

I . this value)

maxLcrlgth Specifies the maximum number of cha'racters or list items allowed. Must be equal to or greater than zero

rninExclus~ve Specifies the lower bounds for numeric values (the value must be greater than this - value)

. . . . .. . . .

: minInclusive Specifi . to this value)

I . . . . . . . ... , ," .... ..A... :,.. ' .. ,,*, ~. '. .. ~,, .. " ., . . . " "," " .... . . .

, Naresh i ~echnologies', Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- -. - . . , . . . . . . . . -. . - -. An IS0 9001 : 2000 Certified Company - Page 3'- http://javabynataraj.blogspot.com 34 of 99.

Page 35: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

--lninl.c!r~cjtli Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero

I pattcrn Def~nes the exact sequence of characters that are acceptable

I totalDiyits Specifies the exact number of digits allowed. Must be greater than zero

I whitcSp;icc Specifies how white space (line feeds, tabs, spaces, and carriage returns) is handled I

I

! . -- .................. - ... . . . . . . - - ...-.-.. ............................ I

. . . . . . . . . . ,

,. Nonatrsmic Types .......................................................................................................................................................................................... !

All 5: XidL Schema's built-in types are atomic, meaning that they cannot be broken down lnto mean~ngful b~ t s . 1

Xidll Scl~erna provides for two nonatomic types: lists and unions. I I

1 ) Lists

1 List rypes are sequences of atomic types separated by whitespace; you can have a list of integers or a list of 1 j dates. i-isis should not be confused with enumerations. Enumerations provide optional values for an element.

/, Lists represent a single value within an element. I

-...... .

1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 i

- I I

I i /

I 1 I

-

1 I

I I

I 1

- - I

I

I

An I S 0 9001 : 2000 Certified Company Page 3s-

r

<xs:simpleType name="DateListM> <xs:list ~temType="xs:date"/> c/xs:s~mpleType>

<xs:elcrncnt narne="Employee"> <xs:com plexType> <xs:sequence> <xs:element name="Salary" type="xs:double"/> <xs:clement name=7itle1' type="xs:stringl'/> <xs:clement name="VacationDays" type="DateListU/>

</xs:sequence> </xs:complexType> </xs:qlement>

Example: XlVlL

<Employee> <Salary>44000</Salary> <TitloSalcsperson</Title> <VacalionDays>2006-8-13 2006-08-14 2006-08-15</~acation~zl~s> </Employee>

http://javabynataraj.blogspot.com 35 of 99.

Page 36: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Union types are groupings of types, essentially allowing for the value of an element to be of more than _ ,

one type. In the example below, two atomic simple types are derived: Rl- lnning Race and Gymnastics. j I

A third simple type, Event , is then derived as a union of the previous two. The E v e n t element is o f I

the Event type, which means that i t can either be of the RunningRace or the Gywtnastics type. 1

Example: XlVlL <Program > <Event>100-meters Vault</Event>

-- - Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I-- - - - - . - - ._ _ - An I S 0 9001 : 2000 Certified Company - -

Pagc 3 - http://javabynataraj.blogspot.com 36 of 99.

Page 37: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. ~ ~ . . . .. ~

"I"",C"t.)-..>7,%@e-wFiD

:Complex Types i 1

I

4) What is a Complex Element?

, complex element is an XML e lement tha t contains other elements and/or attributes.

I : Example: Define a full name of a person I

I

1 As t i x dlayrarn shows, a complex-type element can be empty, contain simple content such as a string, or can contain complex content such as a sequence of elements.

I ,

( 1 <x:; : cornpi ox'l'ypf narne="ful 1nameType" > <xs : sc?cqucnce> <xs:clement name="firstnameM type="xs:stringU/> <XS : (21-cment name="las tname" type="xs : string" />

< / K : : : socguence> I '1 </~:i : <:c~mp I <:xType>

I

l a Note: It IS not necessary to explicitly declare that a simple-type element is a simple type, ~t is necessary to specify that a

1 complex-type element IS a complex type. This is done with the xe : complexType element I -

I Q) How to Define a Complex Element

I

I Complex types are def ined using <complextype> element in t w o approaches

I I .Approach #1: The "person" element can be declared directly by naming the element

! Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

1- . - - - - - - - -. - - - . -- An IS0 9001 : 2000 Certified Company --

Page 3'7- http://javabynataraj.blogspot.com 37 of 99.

Page 38: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

< X S : (! I (:rnori.l. name="person"> <x:; : cornpl (:xl.'ype>

( - . - ,,,., .. : :;(:q~~(:nce>

.( ...,., ,. : . . . (: I orncnt name="nameU type=="xs : s t r i n g u / > ':;<:I : 0 1 crnent name="ageU type-"xs : i n t e g e r " />

< / x s : :~(:(III~., 'rice>

</>;:; : (:ornF) I (!xrl.'ype> </:.::; : c, I .c!rncirlL>

NOTE: <sequence> indicator. This means that the child elements must appear in the same order as they

are declared.

i I Example: i

<r~i~ir~(>>,' ;(: khn r< /name> <<,I(](!>% 6</<3g0>

I

I

Approach #2: The "person" element can have a type attribute that refers to the name of the complex type -

<x:; : (? I (:rri(:rll: name-"person" type="personTypen />

< x s : r:omp I cxrl'ype name="personTypef'> < x S : sc:(qlle.nce>

<xs : el-ement name="namel' type="xs : s t r i n g 1 ' / > <xs : (? l cmcnt name="age" type="xs : i n t e g e r 1 ' / >

</x:; : scclucnce> < / x s : cornp.l.ex'Type>

1 NOTE: Advantage of this approach is several elements can refer the same complex type. < i 1 Example 1

I I I '

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L-. .. - . . . - An I S 0 9001 : 2000 Certified Company .-

~ a g e 3 - http://javabynataraj.blogspot.com 38 of 99.

Page 39: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

---, her-e a r e Cour kinds of complex elements:

1 . Elements with attributes 2. Elements with sub elements 3 . Elements with attributes and text 4 . Elements with sub elements and text

Note: Each of these elements may contain attributes as well!

1.Elements with attributes

,An errlpty complex element cannot have contents, only attributes. I i !

- . .cVc. ...,. . (:I (:rn(:r1\. r~nmc-"product"> 1.1 <x >i : cornplexType>

< x s : CJ ( . ( . r . ibute name--="prodid1' Lype=lTxs : p o s i t i v e I n t e g e r " / >

11 < 1 xi; : complexType> - : />: :I : <! I c1rr\or1 L>

I

It is possible to declare the "product" element like ,below 1-

I ' I l(<x:i : i r I (:rn(:n L name-"product "> I < x : ; : i:ornF, I c?x'l'yy)c>

(x:i : (:ornp.LoxContent> IF <x:; : r c s t r i c t i o n base=l1xs : i n t e g e r n >

1-11 < x s : a t t r i b u t e name-"prodid" type="xs:positiveInteg~r~~/> </x:; : r(:sI:ri.ctj.on>

< / x s : c:omplexContenl:> 111 < / X S : complexType>

I I I n t he example above, The complexcontent element signals that we intend to restrict or extend the

content model o f a complex type, and the restriction of integer declares one attr ibute but does not I introduce any element content.

1 Example

i 2.Elements with sub elements

-

i You can define the "person" element i n a schema, like this:

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I T; . - . - _ . _ . . . . . . ..

An I S 0 9001 :.2000 Certified Company ~ a g m - - ' http://javabynataraj.blogspot.com 39 of 99.

Page 40: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Example

1

1 I I

' I I , 3.Elements with at tr ibutes a n d text , i I 1 I

I I , T h ~ s type contains only simple content (text and attributes), therefore we add a simplecontent element I around the conlent. When using simple content, you must define an extension OR a restriction withln ; Lhe simplecontent element I 1 ) NOTE: Use Lhe extension/restriction element to expand or to l imit the base simple type for the element.

. . - -- -

Naresh i Technologies, Opp. Satyam Theatre, ~ K e r ~ e t , Hyderabad, Ph: 040-23746666,23734842 1

I I . 1 I

i I 1

I

. .. ~.~ ~

An I S 0 9001 : 2000 Certified Company Page 4: -

1 . <~.';:(~lc\rl\(>~~[: r\arne=:"somename">

< ~ : i : ~:OI~\P., DX~,:YPB> <x: ; : s i.mpleContent>

<xs :extension base="baseiype"> . . . . . . . .

</xs : extension> </x:; : si.mpl cContent>

</x:; : c:ornpl ctx'llype> </x:; : o I c>rnctr)L:>

OII

<XS : ( 2 I <:r~i(!r~I; name="somename"> <s:; : c:ornp.l.exType>

<xs : s i mplcContent> <xs: rcs t r j cti.on base="basetypeW>

. . . .

. . . . </x:; : rcs (;ri.cti.on>

</xs:simp1eContent> </x:; : cornp 1 oxType>

</x:j : (2 I (?rncnt:>

http://javabynataraj.blogspot.com 40 of 99.

Page 41: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

I -

<x:; : c>xtcnsion base=llxs : integer1'> <x:;: n Cl:r.i.bute name-"country" type=llxs: string" />

-:/?::; : cx l.cns:i.on> I </x:;: 5 i rnplcContent> < / x:; : c:orn~).I cx1l?ype>

</x:; : (! I (!rrl<:rl L>

Ixample: <:; t,ocs.izc coun try-" france ">35</shoesi ze>

%.Elements with sub elements and text

XML element, "letter", that contains both text and other elements:

11 <x:< : (, I c:rri(~ri 1. namc="letter"> <x:i : c:orrio I c!x'L'ype mixed="truen>

II < X : i : :ic:(juence>

I I < x s : c l ement name-"name" type="xs : stringu/> <x:;: o I cmcnt name=="orderi dl1 type="xs :positiveInteger"/> < x s : c l ement name-"shipdate" type="xs: date1'/> 1) < / x:; : :iaquence>

- < / x:; : ( :Oii l~, l ex'l'ypc> 11 x : L Ior111~111>

F

I

I Example: I I I B h < l P [ lCI>

I)(.o I M r . <name> John Smith</namc>. 1 Y o u r o rclo r <orderid>l032</orderld> w I l l bc st1 ipped on <shipdate>2001-07-13</shipdate>.

/ An enipty element is an element that contains no content, but it may have attributes. The HolnePage element

in the ~rs tance document below is an empty element.

I <Homepage URL=" http : //www . marktwain. cornf1 />

/ ' Indicators -

1 We can cont ro l HOW elements are to be used in documents with indicators.

I There are seven indicators:

i Order ind~cal-ors:

.p\ ---- --

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

--. -- -- - . - - - - -- Page 41-- http://javabynataraj.blogspot.com 41 of 99.

Page 42: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

1 . ,411 2. Choice 3. Sequence

Occurrence indicators:

Group Indicators: I

1. Group name 2. attributeGroup name

I Order Indicators

i I

i Order ~nd~cator-s are used to define the order of the elements. > I '/

i I All Indicator i

t I

The <all> indicator specifies that the child elements can appear in any order, and that each child element - must occur only once:

. . . . - - . . -- < X S : (2 I orn(!nl: name="person">

<>::; : camp I.cxType> <:x : ; : t3 I I >

<x:;: (\ I CI~CTI t narne="fj.rstname" type-"xs: stringM/> <x:; : ( 2 I ornent name="lastnarne" lype="xs : string" />

</x:; : a.L.l.> </x:; : c:orny) I cx1I.'ype>

</.K:;: ( > I (:rn(:r~l:> . . . . - - - --- . - . . . - - - - - -

< 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 (the crninOccurs> and <maxOccurs> are described later).

Choice Indicator

/ The <choice> indicator specifies that either one child element or another can occur: I I

(r,:;: choi ce> <x:;: c ILcmcnt name="servlet-class" type=" xs : string1'/> <x:;: (21 cmcnt name=" jsp-file" type="xs:stringW/>

</x:; : choj cc> < /x:; : c:ornpLexType>

< / x :; : (? l c?rnc \n I->

- - - p p - - -

Naresh i Technologies, Opp. Satyam Theatre, ~ m e e r ~ e t , Hyderibad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company - -. . - - -. - -. . . . . . . . - . . . - ---

Page 48' - http://javabynataraj.blogspot.com 42 of 99.

Page 43: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

3ecgr;ence Indicator

, h e <sequence> indicator specifies that the child elements must appear in a specific order: I

. - . . . - -- -- - --- ~ --

x : ? I o r I name-"servletW> I <x:; : r:onpl crxClype> <\::i : :j(?(qllCrlce>

I <x i< : o I crneri t name="servlet-name" type="xs: stringn/> , ,<:?:; : (! I c!mcnt name-"servlet-cl.assW type="xs: string" />

</>::; : :;(!(1(-1<:nce> I <:/~:j : (:<>rrlp 1 (!xrltype> , <I>::: : c: I (?lri(:r) L:>

.... ....... . -

Occurrence Indicators

) Occurrence indicators are used to define how often an element can occur. 1 I

I Mote: For a l l "Order" and "Group" indicators (any, all, choice, sequence, group name, and group j rcfcrr~ncc) the default value for maxOccurs and minoccurs is 1.

i m a x ~ c c u r s Indicator I ' 7-hc <max~ccurs> indicator specifies the maximum number of times an element can occur: -

i ........-. . -- - ... ---. - ------- I I <x:; : (: i (:r~l(?r)i. r)i~rn(?-tlp~~~~nl'>

<x:; : (:c!m~, I c!x'l.'ype>

cx:;. . (21 crncnt name-" full name" type="xs :

I I < x > ; :c: I c?rnc?nL name-"chj.ld name" - < / x : ; : sc:clucnce>

1 I < /x:; : camp I cx:rype> </x:j : (,: I i!rrlc!n I:> .

. . - - - - -

1 - The example above indicates that the "child-name" element can occur a minimum o f one time (the default

/ value for minoccurs is 1) and a maximum of ten times in the "person" element.

I minOccurs Indicator I I

I The <njinOccurs> indicator specifies the minimum number of times an element can occur: I .......

<XS : (I I c?nic?ri I- riame="person"> <x : ; : c:olrlp I c!xType>

<x:; : :;ocjucnce> <x:j : o.l.cment name="full - name" type="xs: stringq1/> <x:; : c; lement name="chil.d - name" type="xs :stringM IT~~IXO(:(:~~TS--~~~O~~ minOccurs="O" /> '

</x:; : :;cclucnce> . < / x : ; : comp l.exType> < / x :; : (: I c: rric? ri I:>

..........

, . ..-- ........

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

http://javabynataraj.blogspot.com 43 of 99.

Page 44: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

The c:xample above indicates that the "child-name" element can occur a minimum of zero times and a x

maximum of ten t ~ m e s in the "person" element. -

NOTE: To allow an element to appear an unlimited number of times, use the maxOccurs="unboundedl ' statement. i

-1.

NO'I'i~:: rninOccurs and maxOccurs can also be applied to model groups (e.g, xs:sequence) to control ! the 11uniber of times a model group can be repeated.

Group Indicators

I Group ~rid~cators are used to define related sets of elements. 4

1

Elernent G r o u p s

ElcrncriL groups are defined with the g roup declaration, like this:

You must def~ne an all, choice, or sequence element inside the group declaration. The following example de r~ r~es a group named "persongroup", that defines a group of elements that must occur in an exact sequence:

.............. - - <x:; : (7 r:.oilp r~;- ,m.e~"persongroup">

<x:; : :;(!(1(1(?ri(:(>> <x:; : c: l (:rner1C: name="f i r s t n a m e " t ype="xs : s t r i n g w / > <<>i:; : ( 2 1 c:rnenL name="lastname" t y p e = " x s : s t r i n g w / > c,u:; : c; l . o rne~~ t n.arne="bir thday" t ype="xs : d a t e u / >

</x:; : :;c(qu.oncc> < / x s : c~ r.o up>

.......... --

After you have defined a group, you can reference it in another definition, like this:

<x:; : corny) I c:xType name="person in fo"> <x:; : : ; o ( ~ I J c ~ ~ ( : ( ~ >

i x s : CJ r o u p re E="persongroup"/> . c x s : c l c m e n t name="country" t y p e = " x s : s t r i n g " / >

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

An I S 0 9001 : 2000 Certified Com~anv I . . Page 44'

http://javabynataraj.blogspot.com 44 of 99.

Page 45: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Attribute Groups I

I ! I

. ~ t l r ~ b u l c groups are defined with the attributeGroup decla'ration, like this:

The rollowing example defines an attr ibute group named "personattrgroup":

::;:;: < I i I . s i k)u te name-"birthday" type="xs: datew/> I </x:i : t i I I r i i)ui:i:Group>

-- - .- - - - -

Aller you have defined an attr ibute group, you can reference it in another definition, like this:

...... . -. ... 1 <,,c. . : I 1.1. r i 1 G r o u p name="personattrgroup"> ,

1 <any> Element

The <any> element enables us to extend the XML document wi th elements not specified by the schema. I .

.... ... ... - - - <X:j : : ; ( : t ) ( : r r~ t~>

1 x : : I I . name-"person"> <x:: : (:orrip I oxll.'ype>

1 ( <SS : sC(~uC:nce> <x:; : c : . l . ement name="firstnamel' t.ype="xs : stringw/>

I / < x s : c l cment name="lastname" type="xs : stringf1/> <XS : any minOccurs="O"/>

I I < / X S : sc:cluence> < / x s : c:ornp I.cx'rype>

</x:j : P 1 c:mc:rll;>

..... -. - - .-..-. - - - -- .- - - -. --

m I m ? a . E v - ................................. .-

1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

-- -. -. - - - ---- An IS0 9001 : 2000 Certified Company -._-I ........... .... ...

Page 4.5 http://javabynataraj.blogspot.com 45 of 99.

Page 46: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

<x:; : (: I (!il!i!rl l. name-"children"> <s : ; : c:oinp I cxll'ype>

<x:i : :;(:ql~(:nce> < x : ; : (1 1 c!rr~c?nl: name-"chj.lclname" type-"xs: string" r l i ~ l xO(:(:u.rsz-:"unbounded" />

</x:; : :;cqucnce> <is:; : c:c)rny) I cxType>

</x : i : (: I c!rrlor1 L>

farnil\;.x@ ! / T h s XML rile uses components from two different schemas; "perosn.xsd" and "children.xsd": I

NOTE: The <any> and <anyAttribute> elements are used to make EXTENSIBLE documents!

<a nyAttribute> Element

i ' The <~nyAttr ibute> element enables us to extend the XML document with attributes not specified by the 1 schema. 1

person.xsd

- -- - - - - <x:< : :;~:k1(!111<3> <X:j : ( > 1 c1111(:11 1- name-"person">

< x : ; : c:orny) I oxl'ype> <x:; : socquence>

<xs: c l cment name="firstnamel' type="xs: stringw/> <xs: c l cment name="lastnamel' type="xs: string1'/>

</xs : scqucnce> <xs:anyAttribute/> ---

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

-- - An I S 0 9001 :a2000 Certified Company

- - - - - ---- Page 44

http://javabynataraj.blogspot.com 46 of 99.

Page 47: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

( ' rhis XMI. file uses components from two different schemas; "perosn.xsd" and "children.xsd":

i I Overview ............................................................................................................................................................................................. 1 Or-lc of the nice features of XML Schema is that comments about the schema itself can be made within built- i in XMI.. elements. This makes it possible to run a transformation against a schema to builds documentation / in I-ITPJiL or some other human-readable format. -

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- -. - - - - - . - - An IS0 9001 : 2000 Certified Company --

Page 4 7 http://javabynataraj.blogspot.com 47 of 99.

Page 48: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. . - - -- -. -... .~ -. -.

Ar~:.natating a Schema ; 1

.............................................................................................................................................................................................. ' I

! -. , , y... . . . . . . ,~\ ;

i i : . :-; . ;~-:r:,:\ta t i s n element is used to document a schema. It can take two , clci l iei ' l t~: :..s : doc~lm@ntat i r ,n andxs : appInfo , which are used to provide human-readable and ' i i.?iai.:lii5~:-l-?adable notes, respectively. -. I1

i i.:cr :,. -: : :-:::i;<j -.:3 t i i>n element can go at the beginning of most schema constructions, I . . ,. ;r;;,.>. *< , - . ( 7

I:.! ~ i i i I . ; .::-: : :.:::I~en:a,xs : c?1.e.~1en t-, xs : a- t - t r ibu . te , xs : s . m x 1 1 type, xs : coniplexType, xs : gro~iip, . . . . . . . L A .

P. 1 - --,, ,..: . . . . . . ; 1. -1. .? ' ),. . ~2i.i.; ..Group. a, I:.< ...:.. r... ........ !

I - ! -i:: ..:!oc-;i:r:.:cntnt.ior! and xs : a r ~ p I n f o elements can contain any content, including undeclared t:i<:::'ii:.i.il~ acid attributes. This allows the schema author to insert elements (e.g, HTML elements) to structure "I (.I; :~!.i-r.iat ii-ie documentation.

I

XM h Namespaces ,I

XML Namespaces provide a method to avoid element name conflicts.

Name Conflicts ' - * I I n XML, clement names are defined by the developer. This often results in a conflict when trying to mix I

XML. tiocurncnls from different XML applications. - 1 ~ I

TI.li:; XPli carries HTML table information:

This XML carries information about a table (a piece of furniture):

<rl i lmc!>A l-r.i car] Coffee Table</name> <L.J i ( j ~.t!>:~o</Wj.dth> <: I o r i q \.t1>1 %O</l.erlgth>

I II Lhcse XML fragments were added together, there would'be a name conflict. Both contain a <table> ,

i element, but the elements have different content and meaning.

I An XML parser will not know how to handle these differences. I

Solvilig the Name Conflict Using a Prefix

1 Name conflicts in XML can easily be avoided using a name prefix. -== -&.- "-- - - - - - -- -

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L- - - An IS0 9001 : 2000 Certified Company - Page 4'-

http://javabynataraj.blogspot.com 48 of 99.

Page 49: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

( 11,:; xri l carrlcs information about an HTML table, and a piece of furniture: i

- . - -.. -. -- - .. - I

ln I l ~ e example above, there will be rio conflict because the two <table> elements have different names.

1 "

i ! X b i ~ Namespaces - The xmlns Attribute I

( W h c r ~ using pref~xes in XML, a so-called namespace for the prefix must be defined. -

I I Thc namespace is defined by the xmlns attribute in the start tag of an element. -

/ Thc r;cllllcspace declaration has the following syntax. xmlns:prefix= "URI".

1 I : I I c! n n l l n s : f=Ifhttp: //www. sekharit . com/furniture"> < [ : narno>AI:rican Coffee Table</f:name> < i : w i (.]I h > t l O < / f : width> I I < I : i <:nrj i , h > l . Z O < / f : length>

< / r : I ~ : I L ) I (:>

I n t h e example above, the xmlns attribute in the <table> tag give the h: and f: prefixes a qualified I namespace. -

1 W h e n a namespace is defined for an element, all child elements with the same prefix are associated with thc samc namespace.

I ' Narncspaces can be declared in the elements where they are used or in the XML root element:

I i I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

. - -- -- An I S 0 9001 : 2000 Certified Company

~ajjFI-9-- http://javabynataraj.blogspot.com 49 of 99.

Page 50: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

1 Note: Thc namespace URI is not used by the parser to look up information. ..I I i

1 I I !

1 1 / The put-pose is to give the namespace a unique name. However, often companies use the namesp'ace as a I

poini.cr l o a web page containing namespace information. i I -1

< l : l . c . i l > 1 ,::>

< I : r - l ~ i r n ( : > / \ l cican Coffee Table</f :name> < i ::%I i (Jl,h>f3O</f: width> <:I : I (:ri(]!.h>I 2 0 < / f : length>

. < / I : t.<lk) I (!.>

DeT~nir,g a derault namespace for an element saves us from using prefixes in all the child elements. I t has the foilowrr~y syntax: I

i xrn I 11:; " t~i;mo~pilceURI~~ i

1 Thls XML carries HTML table information:

c l 1 I xs I rls "http: //www.w3 .org/TR/htmll/"> I

I This XML carries information about a piece of furniture:

...

< I ( xm I ns--''http: //www. sekharit. com/furnitureW> . <rlalnc:>/\li.rj can Coffee Table</name>

1 < w i cll.h>ilO</width> i ,: i (1r1(31..1.1>1 %0</-[Length> -1

-,z.---- -. .................... .-

Naresh i Technologies, Opp. satyarn Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 -

I. - - - -. - - -- An I S 0 9001 : 2000 Certified Company - . . . . . . . . . . . . . .

Page 5: - http://javabynataraj.blogspot.com 50 of 99.

Page 51: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

-1 j Develop a XSD file for the following xml file?

-.,ol..2. xrr1l I,.:!,:] :-,.;rsion="l. Ow:'>

: . .. . . -. tu>Tove</to> - - !?l-orn>Jani</ f rom> ... heading>Reminder</heading> .h,-dy>Donlt forget me this weekend!</body>

. - < / ~ ~ o i t ! >

. . .. . -. . - -- - -. - - --

: : I r a xmlns: xs="http: //widw. w3 .org/200l/XMLSchema" L-I: ,;, I.il-imespace="http: //www. sekharit . com" :.i-l! ; . : : ;= . "n t tp : //www. sekharit. co~n" i: i.:!?:?n l :F 'ormDefault="qualif ied">

c ... .,,- c: : elernent name="noteW> .-':.::< : co~nplexType>

.is?; : sequence> c:?:s:element name="tof' type="xs:stringl'/> <- . . r .

-:.%.). element name="fromf' type="xs: stringw/> -, .-ia.element ... = . name="headingN type="xs:stringf'/>

cxs: element name="bodyW type="xs: stringM/> ..:/ss : .?f?quence>

- r -.: r:s : coinplexType> . : j :.:s : eI.e~rierit>

r .

I hc <schema> clement is the root element of every XML Schema.

I _ Thc .=schcrna> element may contain some attributes. A schema declaration often looks something like this:

! . . . ~ - .- -- . ' 1 < '?E : ITI~ . ;ersion='ll . Off?>

- <xs:schema xmlns:xs="http://www.w3.0rg/2001/XMLSchemaff ta.rgct:Kamespace="http://sekharit.com" xrnlns=" ht tp: //sekharit . corn" e le rne i -~ tFormDefau l t="qua l i f i ed">

smrs+*~%c.v+: _- - --

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- An IS0 9001 : 2000 Certified Company

Page 5 1- http://javabynataraj.blogspot.com 51 of 99.

Page 52: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

I

----{-efauit namespace - I I

~111111s 1 targetNamespace="http://sekhar~t.com"

-

A+&-- t ~ r ibute name -

xr111115 xs

- - -. - - -. - - - - - - -. -. . . - , -- .. . . . . . . . User defined elements and data types targetlUamespace="http://sekharit.com" in our schema belongs to our namespace such as "http://sekharit.com"

I I I

1 Q ) h o w to Refer a Schema in an XML ~ocument? I

1 U s ~ r ~ q 111~1 schemaLocation attribute. T h ~ s attribute has two values, separated by a space. The first value is the i I

I nanrespace to use. The second value is the location of the XML schema to use for that namespace:

/ schernaLocation="namespace location-of-XML" I -1

Description . .. . -- - --

Elements and data types corn: from the "http://www.w3.org/2001/XMLSchema" namespace.

/

I <r:vte xmlns="h t tp : / / w w w . s e k h a r i t . com" x;r\;:~:s: r is i -" t i t tp : / / w w w . w3. org/2OOl/XMLSchema-instance" x::. i : ::;::h~n;aLocation="http: / / w w w . s e k h a r i t . com n o t e . x sdW>

- - -

Exmaple I L

--- .- -

~mln~:~~=~'ht tp: / /www.w3.org/L001/XMLSchema" Ij I

i 1 I I

<t:c>?:ove</to> <Iroi!~:.~Jani</from> <heading>,Reminder</heading> < ~ , ~ c : ~ , .% ,, :..O;jri ' t f o r g e t me t h i s weekend ! </body> </note.>

. ~ . . . . . ..

i .. .. I j ,

-. . - - clcri-icntt-or-mllcfault

. . - - .-

xrL?:7r- --.- h t t p : / / w w w . s e k h a r i t . corn .=---I . -

spc!cil~cs thc dcfault namespace declaration. This declaration tells the schema-validator that all the elements used in 1 this XML document are declared in the "http://www.sekharit.com'. namespace.

Oricc you have the XML Schema Instance namespace available: \

Elements must be namespace qualified -. . -- - - - - --- - .- - -. - -

you call usc the schemaLocation attribute. This attribute has two values, separated by a space. The first value is the narncspacc to usc. The second value is the location o f the XML schema to use for that namespace:

elementF~rmDefault=~~qualif ied' '

Narcsh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

-- An IS0 9001 : 2000 certified ~ ~ ~ p a n ~ -

Page 5 - http://javabynataraj.blogspot.com 52 of 99.

Page 53: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

.-

11,;. : : . n3::;aLccat i o n = h t t p : / / x ~ . , I w . s e k h a r i t . - corn ----- n o t e . X S ~ 1 ~ ~ -. - ... .- . - --

. Ti,me XMhSchema-instance Namespace ........................................................................................................................................................................................... -,..:

i :.I,: .:~;;:Ll..Schenia--instance natnespace contains only four attributes. Here is a simplified version of the ::;;rl:,;<;!;:.

: 1 .<xs:all ribute name="typen/> I <xs:i~l tr i t~ute name=''schemaLocation"/,

<xs:al tribute name="noNamespaceSchemaLocationlt/~ </xs:sc:horiia> - - - - .- - p-

I I

! A n XSD Example I-

/ l~tlis will dcn~onstrate how to write an XML Schema. You will also learn that a schema can be written in different ways.

/ An XML Document

I Lcl 's have a look a t th is XML document called "shiporder.xml"

I 1 < 1:; t) i p l.o> < I I . c ! rn>

(I. i I. 1 o>ll:rnp.i.re B u r l e s q u e < / t i t l e > I 1 <no l~a>Spcc i . a l E d i t i o n < / n o t e > -

<clu,~riL. i . I+y>l</quant i i ;y> < p r i.c:c?>l 0. 9 0 < / p r i c e >

< / i l.orn> < i l.orn>

< I : i L I o>lli-de y o u r h e a r t < / t i t l e > 1 1 <quariI. i i . y > l < / q u a n t i t y >

............ ---

........ .- ............ - .. .- .- - .- 1 !!EF=-x'=

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

LA.. . . . . -. - An I S 0 9001 : 2000 Certified Company

Page 53 http://javabynataraj.blogspot.com 53 of 99.

Page 54: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

1-llc X M L document above consists of a root element, "shiporder", that contains a required attribute called 1 "oi~li'iid". The "shiporder" element contains three different child elements: "orderperson", "shipto" and

,

"11cr11" I he " ~ t e m " element appears twice, and it contains a "title", an optional "note" element, a 1 " q ~ ~ a ~ ~ l ~ l y " , and a "price" element. ,- 1

I

Thc 111ic above: xmIns:xsi="http://www.w3.org/2001/XMLSchema-instance" tells the XML parser that this --i

docu~ l ien l should be validated against a schema. The line: I

xs, :rioN~mespaceSchemaLocation="shiporder.xsd" specifies WHERE the schema resides (here i t is in the .! s;lii:c_. loldcr as "shiporder.xml").

I

Ci-sate ~n XML Schema I I

Now we want to create a schema for the XML document above.

Wc star1 by opening a new file that we will call "shiporder.xsdfl. To create the schema we could simply I follow l hc structure in the XML document and define each element as we find it. We will start with the

I staridald XML declaration followed by the xs:schema element that defines a schema: I

I / In l h c schema above we use the standard namespace (xs), and the URI associated with this namespace is 1 the Sclicnia language definition, which has the standard value of http://www.w3.org/2001/XMLSchema. I I

i

i Naxl, we have to define the "shiporder" element. This element has an attr ibute and it contains other I

/ elernen.ts, therefore we consider it as a complex type. The child elements of the "shiporder" element is 1 surrot~ndcd by a xs:sequence element that defines an ordered sequence of sub elements: I

( j !

Then we have to define the "orderperson" element as a simple type (because it does not contain any al l r ibulcs or other elements). The type (xs:string) is prefixed with the namespace prefix associated with XML Schema that indicates a predefined schema data type:

I

. . .

<'?xrr: 1 V ( ! r : i i o r , - " I . 0" encodjng="ISO-8859-1" ?> . < x : r : :ic:t1<:111a xrnins:xs="http: //www.w3 .org/2OOl/XMLSchema">

. . . . .

Nexl, we have to define two elements that are of the complex type: "shipto" and "item". We start by , defining thc "shipto" element:

..

I " ...... <x:; : (1 i orlicri I. n.ame="shipto"> i

-- -- ~ i ( " P ; ~ ! ~ ? , ? % .........

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 . .

- .

I L -- . - . - - -

An I S 0 9001 : 2000 Certified Company pageP!7- .- --

http://javabynataraj.blogspot.com 54 of 99.

Page 55: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. -~

I . . ; . : : j ; i;ijlii() I (:xr.l'ypt.>

-.:... :5 : : ~ C ! C J I I ( ? nu-:> -'.;:; : (? I c?rnc:n t riame-="namen type-"xs : stringM/>

I <s:;: :? I cmcnt name="address" type="xs: stringu/> <x:; : ( I I (!~nc?ril: name-"c:j. ty" type="xs: stringM/> <..:.:j: o I c:rneril. name-"country" fype="xs: stringw/>

. , \:,. . c.,, I . . . . . . . . . . . .,k.(q,lc~:nce> . , x:; : i:i)rrip I ox'I1ype> ,I <::>::; : <: 1 ':.,,ri(:rl t ; >

. . . . ... ... ~-

I

Wii.1.) sclicmas we can define the number of possible occurrences for an element with the maxOccurs and i .ninOccurs atlributes. maxOccurs specifies the maximum number of occurrences for an element and I

! rnirlOccurs specifies the minimum number of occurrences for an element. The default value for both nzxOccurs and rninoccurs is I! I

'Vow vJe c;ln der~ne the "item" element. T h ~ s element can appear multiple times inside a "shiporder" I

elciricril. I h ~ s IS specified by setting the maxOccurs attribute of the "item" element to "unbounded" which , nicrll)s LIICIL there can be as many occurrences of the "item" element as the author wishes. Notice that the

i 'nolc" clement IS optional. We have specified this by setting the minoccurs attribute to zero: I I

I ! .-. .- I .,..,:. .. ,.,.... : . i. I :iiri(!ri I . I r1i;1rne=~~ri.ternl maxOccurs="unbounded">

j ( .:;<.:; : (:<l,nf.) I c:xCType> L cx:; : :;c!cqucrlcc> ! ) 1 c : .x> i : (1 I c!r[~(:r~t: name="1:itle" type="xs: stringn/>

0':3: (11 (?rn~nL name='lnotell type="xs: string" minOccurs="O" />

iJ <x:; : o I erncrlt name-"quantityn type=llxs :pdsitive~ntegerll/> (x:;: c: I c:ment name="pri.ceV type="xs :decimaln/>

:/>::; : s e q u e n c e > 11 ~:/i;:i:1:o~n~,1(:xType> I </.u::r : (! I c!rnc!n L>

. -- -. - -

I Wc c,:n now declare the attribute of the "shiporder" element. Since this is a required attribute we spec~fy 1 USC- "rcqu~rcd".

I Note: 1 he al t r~bute declarations must always come last:

-- I I Y : : 1 . r I e - name="orderidIt t y p e = " ~ ~ : string" use="required"/> 1 --

I Here is the complete listing of the schema file called "shiporder.xsd": I

i I , <x:; : ( I I (.IITI(>II 1,. rlame="shiporder">

1 1 < x:; : c:orrlp I (?x'llype>

( x : ; : :;o(qucrlc:c> -

<x:; : o.l.cment name="orderpersonW type="xs : stringu/>

i I <x:; : (:-I crnent name="sh.i.pto"> <xs : c:ompl.exType>

1 I <xs:sequence> <xs:element name="name" type="xs:string"/>

.I 1 <xs : element name="addresstl type=I1xs : string1'/>

L.. - . - An I S 0 9001 : 2000 Certified Company

Page S T - http://javabynataraj.blogspot.com 55 of 99.

Page 56: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

--- <xs:c.lemenL name="country" type="xs:string"/>

</xs: sequence> </xs : complexType>

<ix:; : (2.1 cment> <x : ; : o ILcmcnt name="i. tem" rnaxOccurs="unbounded">

<x:; : complexType> <xs:scquence>

<xs:element name="titlen type="xs:string"/> <xs:element name="notel' type="xs:stringW minOccurs="O"/> <xs:element name-"quantity" type="xs:positiveInteger"/> <xs:element name="pricen type="x~:decimal"/>

</xs:seyuence> < / x s : cornpl.exType>

.:!x:; : o I c?rncr~t> .........

...{ ,,., : :i(?cq~~c;r~ce> ;:A:; : ;I 1.1, r. i bu te name="orderidW type="xs : string" use="required" />

<,I:::; : cc?rnp I oxType> </x : ; : ( 1 I (irriorl 1.>

Divide the Schema I I I Thc prcv~ous design method is very simple, but can be difficult to read and maintain when documents are I C O I I ~ ~ ~ C X . -i

I Ttit. r icxt desrgn method is based on defining all 'elements and attributes first, and then referring to them

1 usliiy ihc r e l attribute.

I I 1

Hcrc 1s the new design of the schema file ("shiporder.xsd"): I x : r xmlns: xs="http: //www ,w3. org/20OljXMLSchema">

< ! t l(! I i ri i I: i on o f simple elements --> < x : ; : (1 1 (:rr~c:ri 1.. r~ame="orderperson" type="xs: stringw/> <X:j :oi(:~n(:ri.L. rlilme="nameV1 type="xs:stringn/> <x:; : (: I ~!rnc;r11. nilme=="address" type="xs : stringu/> <x:; : (.I ! (?rr~(:riL: riamc="cityl' type="xs : stringv/> <x:; : (: 1 (:,ri(!rl 1. riame="country" type="xs : stringw/> <\<:j : (: I crrl(>r1L. rlame="title" type="xs: stringw/> <x:; : o I ornc?r) l- name=I1note" type="xs : string" /> <x:; : i11 (:rr~(;rl L. name="quantityl' type="xs : positiveIntegerU /> <X:j : c: I (:rr1(:ri [. riame="price" type="xs :decimaln /> .

< ! do l i r~ i lion of attributes --> <x:; : ,i t I- r I L ) I ~ ( . c r~ame="orderid" type="xs : string" />

< ! tjc! l. i rl i l:i.orl of complex elements --> < x : ; : c i I o~i-~criI; name==ltshipto">

<x:; : c:ornF) I cxlllype> <x:i : s(;qrl(?rlce> .

ODs.:ZE--.. - ............ .. ---- Naresh i Technologies, Opp. Satyam Theatre, Arneerpet, ~~derabad, '~hi40-23746666,23734842

. . . . . . An I S 0 9001 : 2000 Certified Company -~ -.

Page 5 ' .... http://javabynataraj.blogspot.com 56 of 99.

Page 57: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

1 x i : 1 o r name-"shiporder"> .:,x:r : (:orr~p I oxll.'ype>

,I .<- ., L . - . S O ( I ( I C : I ~ C ~ >

- <xs : c:.l.oment ref="orderpersonW/>

, 'I ' <xs : c l cmcnt ref="shipto" /> <.#<. .,., . . (1 I erneni: ref="item" maxOccurs="unbounded"/>

- + ' / x s : :;(:(~lJ<>rlCe> 1 1 <;::i : iii.l.rj.b~te ref="orderid" use="required"/>

I , ;: / - : i : complcx'i'ype> I < I > . : j . < ! 1 (!rrl(!r\ (.>

I k i n g Named Types I I

The ILli~t-d design method defines classes or types, that enables us to reuse element definitions. This is

( doric by namlng the simpleTypes and complexTypes elements, and then point to them through the type ' a t t r i buLe of the element.

I I-lci-r: i.;,I-hc lhird design of the schema file ("shiporder.xsdU):

. -. - - i 1 I vc ! rs i or)-'!I. Oft encoding="ISO-8859-1" ?>

I I <s:< : :;(:horrld xm1 ns: xs="http: //www.w3. org/2001/XM~Scherna">

i / <x:; : :: i.mp I il'l'ypc name="inttypeW>

C ,.(., ... '. . . r.(>:j I. r: i i:.I::i.on base-"xs : positiveIntegerl'/>

< / x : ; : ..; i rnp I oll'ype>

<x :j : :; i rrip I cl'l'ype name="dectype "> ........- -- . .

..-........... ........... .-

I IYaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L.-- . . . . . . . . . - ... - An IS0 9001 : 2000 Certified Company Page ST-- http://javabynataraj.blogspot.com 57 of 99.

Page 58: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

<,.:.: : i : i 1r11: I o'l'\jpc! name="orderidtype"> : : : i r i o n base="xs : stri.ngM>

..::.:.:i : ; ) ; I I.[.(? rrl value=" [O-91 {6} " / > ..',,',:.::: ?!.::jl*r,; c:Liorl>

<. i' ...., ,, c . . . s i rn1;I orI'ypc>

< : : i I x ' y name="shiptotypeU> _ ..,.: \ , . . . . . I.l, :(.(.{uc!r~(:c!>

c:;.::; : c! I ci111c311L name="name" type="stringtypeH /> ,., ..; : j : ( I I orr~~n l: name="addre~s'~ type="stringtypeW /> ._ ,....., . . (. . . < : .. 1 <!1nc?ri(: name='rci.l;y'r type="stringtype"/> ..:. ::i : < > I ornc?rl t name="country" type="stringtype"/>

.<ix:; : :;(:qi~crlce> . <:;.:::; : (:cirri[) I ox'I'ypc>

< ,... \... c . - c:c)ir~(i I c?x'l'ype name-"shi.pordertypeW> ,:.:X:; : :;(!<jl~(!nC:C>

~-: x . I , . : (1 I (;rn.c:rl L name="orderperson" type="stringtype"/> <A: ; : (: I c?rn.~~1.1: rlame=l'shiptoll type="shiptotypeU/> <;?:.:j : c! I.c:rneri t name=I1i tern" maxOccurs="unbounded" type=" i temtype" />

.<,/s:; : :;(?(ylJ(?TlCC?> c:x...; : :i 1.I.r i.k)uI:c name=="orderid" type="orderidtypeW use="required"/>

'</::s : c:orrIp I c?xrl'ype>

< x c ; : (, i.i?rnc!r> I- name-"shiporder" type="shipordertypeV/>

Thc rcskiction element indicates that the datatype is derived from a W3C XPlL Schema namespace dalatypc. So, t h e following fragment means that the value of the element or attribute must be a string V L I ~ L J C : '

~ .. .~

I I x ; : t - r i o n I .. . - . . . !

I-hc restriction element is more often used to apply restrictions to elements. Look a t the following lines f rom Ihe schema above: -

<x:; : r.c:sl. ri.cl:i.on base="xs : stringu> I in:;: p;~i:l.arn value=" 10-91 (6) " />

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company

- - - . . -. . - - - . . - Page 5 - http://javabynataraj.blogspot.com 58 of 99.

Page 59: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

l ~ i s ir~diciltes that the value of the element or attribute must be a string, it must be exactly six characters i1.l :I row, and I-hose characters must be a number from 0 to 9.

i Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- - - -. - - - An I S 0 9001 : 2000 Certified company -- p--

pageP5T--- http://javabynataraj.blogspot.com 59 of 99.

Page 60: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML application development - I

I

1 4.) What is an XML application?

r3 A program that works with XIVIL document is known as XML application I

13 To work with XIVlL documents we need API

! / 4.) What is JAXP?

~3 JAXP stands for Java API for XNlL Processing G JAXP is a specification from W3C.

G JAXP is an API from Sun

G Using JAXP API we can process XML documents in two methodologies

o DOM

o SAX

G JAXP API is implemented by multiple vendors(xcerses.jar, crimson.jar, oraclev2.jar ... etc)

* There are some parsing APls which are proprietary (xml4j.jar, xmlbeans.jar ... etc)

r3 From Jdk 1.5 onwards, jdk itself has xcerses.jar(Apache) implementation.

DOM I

c3 DOM stands for Document Object Model I

c3 I t is hierarchical model(tree based model) I

0 At a time total document will be loaded into the memory as a tree structure. . I

c3 In DOM each element is called Node

+ DOM is R/W parser. a 1 13 Before jdk 1.5 there was only JAXP API as a part jdk, But there was no implementation.

I Q From jdk 1.5 onwards, jdk has JAXP API and xerces.jar(Apache) implementation. !

If we want different implementation, we need t o set corresponding system properties 2nd we need to ! add corresponding jar file in the class path.

I !

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company I - -- - --

Page l- http://javabynataraj.blogspot.com 60 of 99.

Page 61: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

.- -- ..- ... .. . - ~~~ . - . ~ .--.p.......-p-.. -- -- -

~ XbIL By Mr . SekharReddv i

- DOM Architecture -

:teps to work with DOM

-2tep 1 : create DocumentBuilderFactory I ) ~ ( : L I I I I C T I 1.1311 i 1 d ( 3 r1~'iic:I.o ry f d c 1 . 0 ~ ~ -

DocumentBuilderFactory.newInstance();

Step 2 : create DocumentBuilder DocumerltBuilder builder = factory.newDocumentBuilder();

Step 3 : get inputstream of xml file ClassLoader cl - WomReader.class.getClassLoader(); Inpu-tS.tream is - cl. getResourceAsStream("XML File") ;

Step 4: parse xml file and get Document object, by calling parse method on . QocumentBuilder object.

Document document = builder.parse(is);

Step 5: Traverse DOM tree using document object and access XML data

Q.) Develop an XML application which can read, write and modify xml documents using DOM? -

- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

. I -

An IS0 9001 : 2000 Certified Company - . . --- - - - - - - - --

- Page 2 i

http://javabynataraj.blogspot.com 61 of 99.

Page 62: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

.. -. - - - - - - .- .- - - - - -- - -- - - - - - - -- - .

XML By Mr. SeltharKeddy7

1:. i: 1-1-1 p 3 1-5.er .[AT a ! , 51'C

... '... o .::.:: ~ ~ ~ , ~ ~ ~ E I : ~ C I ~ ~ ~ ; . X ~ I - I I , C I I ~ ~ - I ~ . C U ~ - I ~ ~ ~

,I i{ ,-, 2 I I . ..-.. Fr-I i .- ;: .;..

>: en~ail . , ;rnl >I: eti-lpli:~;..~~.::<r-l-~I

4 ..>.. !~i>t-17,~v.~rFl-]rf::. r j ~ - - -.c= - . -- - 7 8 - 1 : t l l ,L [* -u t e : j

: ; ........ . . : o ak,j a-*.:a

i . .... j. .... : . ~ . c ; ~ ~ [ l c t - l ~ ~ : ~ ~ e ~ t i n c l , ( t r a i a -

a - l..? i - ~ t - ~ - ~ - . .,j~,r~,--~[..s 9 - p,., ~~.+-~-,l ,LI;~-I>,I-%zcI -1 1 nc;t-i-~ Et-~-ipIoyeeRezcl~r.,ja~~~.~ [?gt-liRea~/el*,ia.a;.:;a

E. t - t ip I~y~~, i ,y ja

rr~.ysreclcl~.xr~~l,ilot~-l,~~p.~~t~

1 . .i , RQ c if;{:<(?.~l L Fi I t, ia12.a ..=- ! F1.E 5:c.;iztet-1-1 Libra

DomReader.iava I

1. package com.ysreddy.xml.dom.read; ( 1 2. I

~ !

3. import java.io.IOException; I

4. import java.io.InputStream; i . . I

5 . , . '. ,

6 . import javax.xml.parsers.DocumentBuilder; 7 . import javax.xml.parsers.DocumentBui1derFactory; 1 8. import javax.xml.parsers.ParserConfigurationException; 9. : i 10. import org. w3c. dom. Document; 11. import org. w3c .dom. Element; I

I 12. import org. w3c. dom. Node; 13. import org.w3c.dom.NodeList; i

I 14. import org. xml . sax. SAXException; 15. 16. public class DomReader { I 17. public static void rnain(String[] args) throws ParserConfigurationException, i

18. SAXException, IOException { 1 19. / / create DocumentBuilderFactory 20. DocumentBuilderFactory factory = DocurnentBuilderEactory . newInstance ( ) ; I 21. 22. / / create DocumentBuilder 1 2 3 .

i DocumentBuilder builder = factory.newDocumentBuilder();

24. I I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company i

- - - - --

Page 3 - http://javabynataraj.blogspot.com 62 of 99.

Page 63: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- -. -- - . - - .- - - -- -- - ---

XML Bv Mr. ~ekharReadv I

/ / get inputstream of email.xm1 file ClassLoader cl = DomReader.class.getClassLoader(); Inputstream is = cl.getResourceAsStream(

"com/ysreddy/xml/dom/config/email.xml");

/ / parse xrnl file and get Document object Document document = builder.parse(is);

/ I get root element of xml document Element rootElement = document.getDocumentElement();

;/ get <subject> tag value Node first = rootElement.getFirstChild(); Mode sibling = first. geth1extSibling ( ) ;

Node firialMode = sibling. getFirstChild ( ) ;

String value = finalNode.getNodeValue(); System.out.println(va1ue);

/ / get <from> tab vlue NodeList nodeList = rootE1ement.getE1ementsByTagName("froml'); Node fromElement = nodeList.item(0); Node fromChild = fromElement.getFirstChild(); String fromvalue = fromChild.getNodeValue(); System.out.println(fromValue);

1 I

Employee.iava -1. package com. ysreddy. xml . dom. read; 2. 3. public class Employee {

4. private String name; 5. private int id; .. 3. private int age; 7. private String type; - -

Naresh i Technologies, Opp. Satyam Theatre;Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

Page 4 http://javabynataraj.blogspot.com 63 of 99.

Page 64: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- - - --- . By Mr. SeltharReddv- , XML

public Employee ( ) {

I

public Employee(String name, int id, int age, String type) this.name = name; this. id = id; this .age = age; this.type = type;

J

public String getName(j {

return name; 1

public void setName(String name) {

this.name = name; 1

public int getId() {

return id; I

public void setId(int id) {

this.id = id;

public int getAge ( ) {

return age; 1

public void setAge(int age) {

this.age = age;

public String getType() {

return type; 1

public void setType(String type) {

this.type = type; I

@Override public String tostring ( ) {

return "Employee Details : name : " t name t " age t id t " type:" t type;

: I1 t age t " id:" 1

\

DomEmployeeReader. java 1. package com.ysreddy.xml.dom.read;

1 i

2. I - Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I

- . - An I S 0 9001 : 2000 Certified Company !

Page 5 ' -

http://javabynataraj.blogspot.com 64 of 99.

Page 65: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

,XML By Mr. SekharReddy

1' 3. import java. is. I O E : i ? p t i o r l ;

, 4. impcrt l a v a . io. InputStream; 5 . import java. util ..ArrayList;

i 6. import java. util. List; 7. 8. import javax.xml.parsers.DocumentBuilder;

i 9. import javax.xml.pars~r~.DocumentBuilderFactory; ' 10. iniport j a.-ax. rxnl . par-sers . ParserConfigurationExcept ion;

, 11. import ong.w3c.dom.Document; import orq. ~ 3 z . dom. Element; import org. w3z. dom. Node; import org . i.i3c. dom. Idodelist; import org. xml. sax. S,AXException;

puollc class DomEmployeeReader {

public static vold main(Strlng[] args) {

/ / a) Getting a document object Dozument document = parseXmlFile();

/ / b) Get a list of employee elements List<Employee> employees = parseDocument(document);

/ / C) Iterating and printing printData (employees) ;

private static List<Employee> parseDocument(Document document) {

List<Employee> employees = nerd ArrayList<Employee>();

Element rootElement = document.getDocumentElement(); NodeList empNodelList = rootElement.getElementsByTagName(l'employee'l) ;

for (int i = 0; i < empNodelList.getLength(); i++) {

Element empElement = (Element) empNodelList.item(i); Employee employee = getEmployee(empE1ement); employees.add(emp1oyee);

1

return employees;

1

private static Employee getEmployee(E1ement empElement) {

String name = getTextValue (empElement, "name") ; int age = getIntValue (empElement, "age") ; int id = getIntValue(empElement, "id"); String type = empElement .getAttribute ('Itype") ; Employee employee = new Employee(name, id, age, type);

54. return employee; 55. 1 56. 57. private static int getIntValue(E1ement empElement, String tagName) {

I

Naresh i Technologies, Opp. Satyam Theatre, ~mee ipe t , Hyderabad, Ph: 040-23746666,23734842

- An IS0 9001 : 2000 Certified Company

Page 6 http://javabynataraj.blogspot.com 65 of 99.

Page 66: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

~ ... ~~. - ~ ... -- - ~ . ~-.. .- - ~~ .

XML By Mr. SekharReddy-\ 1

\

I 5 8 . rc-tvrri I!-;-ir,;?r. par se111t (getTexti'alue [empElement, tagIdame) ) ; . - 1 - .

) 5 9 . 1 60 . -.\ :

1 : 6 1 . \ _ ! private static String getTextValue(E1ement empElement, String tagName) {

1 6 2 . blodeList nl = empElement.getElementsBy4TagName); -- 1

6 3 . Node namzNode = nl . item (9) ; . i I

. ,

: 6 4 . Mode textNocie = nameNode.getFirstChild(); I

1 6 5 . -i I String nalne = textNode. getNodeValue ( ) ; , I

, , I 66 . returr! narns; i 6 7 . 1 I ,

I I 6 8 . / /

1 6 9 . ,

private static void printData(List<Employee> employees,) { _. i

/ 7 0 . j .i 1

1 71 . for (Employse employee : employees) { ~ 1 7 2 . System. out. println (employee) ;

' 73 . i i 1 7 4 . - ,

I 7 5 . 1 I I

1 7 6 . . i 1 7 7 . private static Document parseXmlFile() { i. .,! i

7 8 . Docu~~entBuilderFactory factory = DocumentBuilderFactory.newInstance(); I

7 9 . DocumentBuilder builder; I' : I,.

8 0 . Document document = null; I 8 1 . try { L_l!

8 2 . builder = factory.newDocumentBuilder(); 'i ! 1 8 3 . Inputstream is = DomEmployeeReader.class.getClassLoader() .' .. I 8 4 . .getResourceAsStream( -

I 85 . "com/ysreddy/xml/dom/config/employee.xml"); I i - 1

86 . document = builder .parse (is) ; ,. ..

87 . ) catch (ParserConfigurationException e) { I 88 . e .prirltStackTrace ( ) ;

I

89 . } catch (SAXException e ) {

90 . e .printStackTrace ( ) ; ~' I ; I

91. } catch (IOException e) {

92 . e.printStackTrace ( ) ; 93. 1 (' . ' . ,

' I . .. ,

94 . I I

95 . return document; /

1 96 . 97 . } , i

\ I Book. java 1; package com.ysreddy.xm1.dom.create; (

I

2. I !

3. public class Book { i

4. private int id; I 5. private String author; i

6. private String title; 7 . 8 . public Book0 {

l r

9 . 1 1 0 . 11. public Book(int id, String author, String title) { I

I 12. this.id = id; 13. this-author = author;

I

I I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Wyderabad, Ph: 040-23746666,23734842 I

An I S 0 9001 : 2000 Certified Company i ----- --- p a g e l -

http://javabynataraj.blogspot.com 66 of 99.

Page 67: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML By Mr. SekharReddy 1

chis.titls = title; 1

public int getId() {

return id; I

pilbli\; -raid setId(1nt id) {

rhis.id = id; I

public String getAuthor() {

return author; 1

public void setAuthoriString author) I this.author = author;

i

p u b l i ~ String getTitle() {

return title;

1

public void setTitle(String title) {

this.title = title; i

r3ookDomCreating.java 1. package com.ysreddy.xml.dom.create; ) & . 3. lmport java.io.IOException; 1. lmport j ava. util. ArrayList ; 5. lmport java.utl1. Iterator; C 3 . lmport j ava. util . List; 7. 9. lmport javax.xml.parsers.DocumentBuilder; 3 . lmport ~avax.xml.parsers.DocumentBuilderFactory; 10. lmport javax.xm1.parsers.ParserConfigurationException; -1. 12. lmport org.w3c.dom.Document; ' 3 . import org.w3c.dom.Element; 14. lmport org.w3c.dom.Text; ' 5 . ~ 6 . import com.sun.org.apache.xml.internal.serialize.0utputFormat; 17. lmport com.sun.org.apache.xml.internal.serialize.XMLSeria1izer;

-- - 8 . 19. publlc class BookDomCreating {

0. public static void maln(String[] args) {

21. / / a) Load Data. '2. List<Book> books = loadData(); 23.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

Page 8-- http://javabynataraj.blogspot.com 67 of 99.

Page 68: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

~ . . -- ~- ~- - ~~ ~ -. . - ~ -- -. . .. .

XML By Mr. SekharReddv -, i

. , / / b) Getting an instance of DOPI. Docume~t dom = createDocument();

/ / c) Creata thz root element Books createDOMTree(d~m, books);

/ / d) Serialize DOPI to FileOutputStream to gecerate the xml file / / "book.xn~1". printToFile (dorn) ;

private static List<Book> loadData() {

List<Book> books = new ArrayList<Book>(); books. add (new Book (1001, "Kathy Sierra", "SCJP") ) ; Dooks.add(new Bock(1002, "James Gosling", "Java Architect")); return books;

1

private static Document createDocument() {

Document dom = null;

/ / get an lnstance of factory DocumerltBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try I

/ / get an instance of builder DocumentBuilder db = dbf.newDocumentBuilder();

/ / create an instance of DOM dom = db. newDocument ( ) ;

I catch (ParserConfigurationException pce) {

pce.printStackTrace(); I

return dom; 1

private static void createDOMTree(Document dom, List<Boak> books) {

/ / create the root element Element rootEle = dom. createElement ("books") ; dorn. appendchild (rootEle) ;

Iterator<Book> it = books.iterator(); while (it. hasNext ( ) ) {

Book b = it.next(); / / For each Book object create element and attach it to root Element bookEle = createBookElement(dom, b); rootEle.appendChild(bookE1e);

1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

An IS0 9001 : 2000 Certified Company I_ 1

Page 9 - http://javabynataraj.blogspot.com 68 of 99.

Page 69: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML Bv Mr. SeltharReddv ~ private stati-c Elemeni ireateBookElement (Document dom, Book b) {

Element bookEle = dom. createElement ("book") ; bookE1e. set4ttribute ("id", String.valueOf (b.getId ( ) ) ) ;

/ / create author element and author text node and attach it to / / bookElement Element authEle = dom.createElernent("a~thor~~); Text authText = dom.cre~teTextNode(b.getAuthor()); authEle.appendChild(authTsxtj; bookEle.appendChild(authEle);

//create title element and title text node and attach it to bookElement 1

Element titleEle = dom.createElement("tit1e"); Text titleText = dom.createTestMode(b.getTitle0); titleEle.appendChild(titleText); bookEle.appendChild(titleE1e);

return bookEle; I

1

private static void printToFile(Document dom) { I

try i / / print OutputFormat format = new OutputFormat(dom); format.setIndenting(true);

/ / to generate output to console use this serializer XMLSerializer serializer = new XMLSerializer(System.out, format);

/ / to generate a file output use fileoutputstream instead of / / system. out / / XMLSerializer serializer = new XMLSerializer(new / / Fileoutputstream (new File ("D: \\book.xmlT1) ) , format) ;

} catch (IOException ie) {

ie.printStackTrace(); 1

1

1 companv.xml I 1. <?xml version="l. 0" encodlng="UTF-8" ?> -

2. <company>

1 3 - <staff id="lW> 4. <firstname>yerragudi</firstname>

i 5 - <lastname>sreddy</lastname> 6. <nickname>ysr</nickname>

1 7 . <salary>lOOOOO</salary> i

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I ! -- An IS0 9001 : 2000 Certified Company

Page 1 0 http://javabynataraj.blogspot.com 69 of 99.

Page 70: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML By Mr. SeltharReddy . ,; -

1

r 7 i ModifyXMLFile.java . .. . I ,

1. package com.ysreddy.xml.dom.update; !

2. ' \ ; / I 3. import j aua . io . File; 4. impcrt java.io.10Exception; ' \.: I

5. import java.io.InputStream; "I 6. I

\! 7. import javax.xml.parsers.DocumentBuilder; .i ,i 8. import javax.xm1.parsers.DocumentBuilderFactory; !

I ~, 9. in!port javax.xml.parsers.ParserConfigurationE~ception;

1;

10. import j avax. xml. transform. Transformer; , < , 11. import javax.xml.transform.Transformer~~ption;

12. import javax.xm1.transform.TransformerFactory; ' j

13. import javax.xml.transform.dom.DOMSource; 1 14. i.mport javax.xml.transform.stream.StreamResult; , I

15. 16. import arg.w3c.dom.Document; , .

\ '- "I

17. import org.w3c.dom.Element; , 1.8. import org.w3c.dom.NamedNodeMap; '

19. import org. w3~.dom.~ode; 20. import org.w3c.dom.NodeList; L~ , i - 21. import org.xm1.sax.SAXException; 22.

i i /. ,

23. public class ModifyXMLFile { -

24. ' 1 25. public static void main(String argv[J) { /

26. ' I 27. try { ,, i 28. Inputstream compstream = ModifyXMLFile.class.getClassLoader() 29. .getResourceAsStream( i

, .. 30. "com/ysreddy/xml/dom/config/company.xml");' '.

31. ! 32. DocumentBuilderFactory docFactory = DocumentBuilderFact-ory / . - ' , . 3 3 . . newInstance ( ) ; >. I'

34. DocumentBuilder docBuilder = doc~actor~.new~ocument~uilder'(); I 35. Document doc = docBuilder.parse(compStream); 36. 1 37. / / Get the root element 38. Node company = doc.getFirstChild(); 39.

, I 40. / / Get the staff element , it may not working if tag has spaces, 41. / / or , I 42. / / whatever weird characters in front . . . it's better to use 43. / / getEYementsByTagName() to get it directly.

I .

44. / / Node staff = company.getFirstChild0; \

45. 46.

I - / / Get the staff element by tag name directly 47. Node staff = doc.getElementsByTagName("staff").item(o); 1

I 48. 4 9 . / / update staff attribute 50. NamedNodeMap attr = staff.getAttributes0; I 51. Node nodeAttr = attr.getNamedItem("idn);

. .. . - , . . . . . . . . . . . , . . . . . . . . . . . . - , . . . , . . . . . . . . . , , , . , . , . ,. . . , .. , , . . . , , , , . . . . . . . . . . . . . , I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 ,

-- An I S 0 9001 : 2000 Certified Company I

Page 1 - http://javabynataraj.blogspot.com 70 of 99.

Page 71: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. XML

/ / a~pend a new node to staff Element age = doc. createElement ("age1') ; age. appendchild (doc. createTextNode ( "28") ) ;

staff.appendChild(age);

/ / loop the staff child node NodeList list = staff.getChildNodes();

for (int i = 0; i < list.getLength(); i++) {

Node node = list.item(i);

/ / get the salary element, and update the value if ("salary".equals(node.getNodeName()))

node. setTextContent ("2000000") ; 1

/ / remove firstname if ("firstname".equals(node.getNodeName())) {

staff . removechild (node) ; 1

/ / write the content into xml file TransformerFactory transformerFactory = TransformerFactory

. newInstance ( ) ; 81. Transformer transformer = transformerFactory.newTransformer(); 52. DOMSource source = new DOMSource(doc); 83. StreamResult result=new StreamResult(new File("D://modify.xmi")); 84. transformer.transform(source, result); 35. 86. System.out .println(llD~ne") ;

} catch (ParserConfigurationException pce) { - .

pce .printStackTrace ( ) ;

1 catch (TransformerException tfe) {

tfe .printStackTrace ( ) ;

} catch (IOException ioe) {

ioe.printStackTrace(); } catch (SAXException sae) {

sae.printStackTrace0; 1

1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- An I S 0 9001 : 2000 Certified Company Page 1 2

http://javabynataraj.blogspot.com 71 of 99.

Page 72: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

... ........ -. . ..... .. .-.. .. . . . . - . . . ... ~, - ,

XML Bv Mr. SeltharRedd~r -. I

SAX I

0 The Simple API for XML (SAX) is a serial access parser API for XNIL. I

1

It is an event-driven model for processing XML, which implements the technique to register the , ~ handler to invoke the callback methods whenever an event is generated.

r=, Event is generated when the parser encounters a new XML tag I I

'

4.) What are the difference between DOM and SAX?

- -- - SAX PARSER

I

i _ -- - - - - - . i OM is Docunle~lt Object Model .4PI for XML I SAX is a Siinple API for XML

!

: 1

IIOM is a tree model parser

................. _ ... .. - ............. DOM PARSER

. - ... . -. ..-.. ..... - . -. I SAX is an event based parser

. . . . . . ... L- I I Stores the entire XML document into memory 1 Parses node by node A

/ DOM is read and write parser.

i I before processing - . -. . - -. -- -- -- - - - - - -- - - - -. - - - - - Occupies 111ore memory

( SAX is read only parser

Occupies less memory

. . ........................................ .....

Randoill Access 1 Sequential Access

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

Preserves comments I Doesn't preserve comme~lts

I Slower than SAX ... .-.....

) Faster than DOM

SAX Architecture

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 -

An I S 0 9001 : 2000 Certified Company .-

I Page 13 -

http://javabynataraj.blogspot.com 72 of 99.

Page 73: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML - . . -

By Mr. ~ e k h a r ~ g d d i

List of !<.&X parser rriettlod calls l:i 1-1 :; e l:{ u e n c ei or-I 'I,' 111 u P

Dolzur-rientHandler implementatinn

i ! i 2

; I ' . ,'$, z , $ $ + % ? d ? : : . $ { : $ . j ; ; : i j ! & $ , f i ' xt711(?5-.-..- ' "> (<,: $$*?. 3

l - ~ . I .A - * mi. c o 1-1-1 , -. . .~ , ~ -. *e -". "z !e +. ,. x , , ~ ~ ~ ~ -- . ,.I . . : , > > % a 8 % , , ! j

-w.

:?*,'.;;~;l;:4~,-.::-, $r? I . > . ~",>{$~.:;;>><-<..;; ;-;.;; <;,r,t:;- 1 I $ 5 ;

I $ - .,.

j : .=I:,!~ 17-1 a i 13. I e *. - , ,. - " " ,. ... , - ,.j -1- j.. .. ...... >,? .:~slg',i;;:gylfgr:: *' -#i$*^ r

1 1 ., ̂" ^ . ",, , .^ ;, _ _. ;. _ , _. ̂ _

3 < i !

Steps to work with SAX:

Step 1: Implementing the required handlers:

public class SAXXMLParserImpl extends DefaultHandlerI ... }

7tep 2: New instance of SAXParserFactory

SAXParserFactory factory = SAXParserFactory.newInstance(); * I --

Step 3: New instance of SAX Parser: " - * - - - " - - - w " " - " ?

SAXParser saxparser = factory.newSAXParser(); - - - - - - - * - - - - - i I I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Wyderabad, Ph: 040-23746666,23734842 i An IS0 9001 : 2000 Certified Company

I I

--2

Pagc 14 http://javabynataraj.blogspot.com 73 of 99.

Page 74: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML Mr. SekharRedd~ - 1

Step 4: Parsing the XML document:

-: Fa1 s e r . parse ( new Flle (XSIL F I L E TO BE PARSED) , -, - - - - I

new SAXXMLParserImpl() ) ;

Q.) Develop XML application where you can read employee.xml file using SAX parser? I

Employee.java 1. package com.ysreddy.xml.sax.read; 2. 3. public class Employee {

4. private int id; 5. private String name; 6. private int age; 7 . private String type; 8. 9. public Employee ( ) {

10. 1 11.

f i

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I An IS0 9001 : 2000 Certified Company !

Page 1F;F - http://javabynataraj.blogspot.com 74 of 99.

Page 75: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- ~ ~ ~ ~ ~ ~ ~ ~ . - . - - - . - - . - - p . - - - ~ - - - ~ ~ - - - - - - - p - - ~- ~ - .~~ . . -

XML Bv Mr. SekharReddv . i

publi- Employes (int id, String name, int age, String type) {

this.id = id; this.name = name; this.age = age; this.type = type;

I

public int getId() {

return id; I

public void setId(int id) {

this.id = id; 1

public String qetName() {

return name; I

public void setName(String name) {

this.riame = name; 1

public int getAge ( ) {

return age;

public void setAge(int age) {

this.age = age; 1

public String getType() {

return type; 1

public void setType(String type) {

this.type = type;

@Override public String tostring0 {

return "Employee Details -- Eid :"+id + " Name : "+ name +" Type : "+type ;

1

EmplyeeHandler.iava -1. package com.ysreddy.xm1.sax.read;

2. 3. import java.uti1.ArrayList; 4. import java.util.List; 5. 6. import org.xml.sax.Attributes; 7. import oTq.xml.sax.SAXException;

+ " Age : "+age

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

Pagc 16 http://javabynataraj.blogspot.com 75 of 99.

Page 76: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

~ ~~ ~ ~ ~- - ~ --

I XML

8. inpor t erg. xml. sax. hel .p=rs . t- '- 05faultHandler; 9. 10. public class Emplo_;~esHandler extends DefaultHandler (

11. pr ii7ate Emplo:;.-e tempEmp; 12. private String tempVal; 13. private List<Ernployee> emps = new ArrayList<Employee>(); 14. 15. @Override 16. public void startDocurnent ( ) throws SAXException {

17. Systeni. out .println ( " . . . . DOCUMEDI'T STARTED. . . " ) ;

18. 1 19. 20. @Override 21. public void endDocument() throws SAXException {

22. for(Emp1oyee employee : emps) 23. System.out.println(employee); 24. j

25. 26. @Override 27. public void startElement(String uri, String localName, String qName, 28. Attributes attributes) throws SAXException {

29. / / Systen~.out.println("\n . . . . starting...."); 30. / / S y s t e m . o u t . p r i n t l n ( " U R 1 : " t uri) ; 31. / / System.out.println("1oca1Name: " t localName);

' 35. if (qName. equalsIgnoreCase ("employee") ) { I , .i 36. / / create a new instance of employee

\' '1 37. tempEmp = new Employee ( ) ; I

38. tempEmp. setType (attributes .getvalue (lltypel') ) ; , ',

39. 1 40.

'I I

41. 1 42. 43. @Override C

1 I 44. public void characters(char[] ch, int start, int length) ' - i

45. throws SAXException { I

46. / / System.out .println ("\rich: "tch) ; 47. / / System.out.println(I1start: "+start); ,, 1 48. / / System.out.println(I'1ength: "tlength); I

49. / / System.out.println("va1ue: "+new String(ch,start,length)); _ I I 50. tempVal = new String(ch, start, length); k,

51. 52. I (

I 53. 5 4 . @Override I

7

55. public void endElement(String uri, String localName, String qName) I

56. throws SAXException { 1 C

57. / / System.out .println (ll\n.. . . ending.. .-. ") ; 58. / / System.out.println("UR1: " t uri); 1 59. / / S y s t e m . o u t . p r i n t l n ( " l o c a 1 N a m e : " t 1ocalName); 60. / / System.~ut.println(~IqName: " t qName); I 61. if (qName .equalsIgnoreCase (I1employee") ) {

(., 62. / / add it to the list

I . . . . . . , . . , . . . . . . .. . , . , . . . . . , . . , , , , , , , , . . , , .

. . I

Naresh i Technologies, Opp. Satyam Theatre, ~meer~et, H'yderabad, Ph:040-23746666,23734842 An IS0 9001 : 2000 Certified Company

- . . -~ - ---Pup . - -- I

Page 17 ' - http://javabynataraj.blogspot.com 76 of 99.

Page 77: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- - . .- ---. - - ...- .- - .

XML Bv Mr. ~ e l t h a r ~ e d d v - . ;

1 else if (qMame . equalsIgnoreCase ("name") ) {

tempEmp. setIdame (tempVal) ; } else if (qName.equalsIgnoreCase("id")) {

tempEmp.setId(Integer.parseInt(tempVal)); } else if (qName. equalsIgnoreCase ("age") ) {

tempEmp.setAge(Int~ger.parseInt(tempVa1)); I

SaxParserDemo.java 1. package com.ysreddy.xml.sax.read; 2. 3. lmport java.io.IOException; 4. 5. lmport javax.xml.parsers.ParserConfigurationExcept~on; 6. lmport javax.xm1.parsers.SAXParser; 7. import javax.xm1.parsers.SAXParserFactory; 8 .

9 . lmport org . xml . sax. SAXExceptlorl; 10. 11. public class SAXParserDemo {

-12. publlc statlc void main(Strlng[] args) throws ParserConf~gurat~onExcept~on, 13. SAXException, IOException {

~ 4 . SAXParserFactory factory = SAXParserFactory.newInstance(); 15. SAXParser parser = factory.newSAXParser(); 16. parser.parse(SAXParserDemo.class.getClassLoader().getResourceAsStream( 17. "com/ysreddy/xm1/sax/config/emp1oyee.xm1) new EmployeeHandler()); 18. 19. 1 2 0 . 1 4.) Develop java application to validate XNlL document against XSD?

r L+$ c~~ti~.. jzreddy.xt-nI, iaxp.~~aIidat~~r JAXPVaIidator.java

A f& com.yrre~ldy.xn~l .sax.~.~~l idatcr \ A*.- !J) SMExTern aI'vCaI idator.; a > ~ a

. ,p"j S A M t i t r r n a l V a l i d a t a r . j ava ,me JRE 5ystct-n Library f5i.!1-1 f l 'i., 1 ,6.f; I-: 4

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

.- An IS0 9001 : 2000 Certified Company

Page 18 -- http://javabynataraj.blogspot.com 77 of 99.

Page 78: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

r-.~.-. -~ ~. ~- ~ ~ - .~ .. ~ ---- - ~ -..-.p---.---p-

XML Bv Mr. SekharReddv. - I

message.xm1 ' I /

I 1. <?xml version="l.O" encoding="UTF-8"?> 2. <m:message xmlns:m="http://ysreddy.com/java/xml/typesl~ 1 3. xm1n:;:xsi="http://www.w3.org/2001/XMLSchema-instance1'

[ I

4 . xsi:schemaLocation="http://ysreddy.com/jva/x/type~ file:///E:/Y.S.Reddy/XML/xsd- 5. examples/xsd/message.xsd"> ' I 6 . 7 . <m:from>[email protected]</m:from> 8. <m:to>ys@gma~l.com</m:to>

- < I 9 . <!--<m:subject>somth~ng somethlng</m:subject> --> I 10. </m:message>

SimpleErrorHandler-java - I 1. package com.ysreddy.xml.errorhandler; 2. i 3. import org.xml.sax.ErrorHand1er; 4. import org.xml.sax.SAXException; 1 5. import org.xm1.sax.SAXParseException; 6. 1

- 7. publlc class SimpleErrorHandler implements ErrorHandler {

8. publlc void warning(SAXParseException e) throws SA~Exception { 1 9. System.out.println(e.getMessage()); . 10. 1 11. I 12. public void error(SAXParseException e) throws S~XException {

I I

I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

-- -- An I S 0 9001 : 2000 Certified Company

Page 19 , http://javabynataraj.blogspot.com 78 of 99.

Page 79: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

-~ ~. .. ~

By Mr. SekharReddv !

- 1 3 . System.out .println (e. qeti~I~ssaqe i ! ) ;

14. 15. 16. public void fatalError(SAXParseException e) throws SAXException {

1 17. S\.'stem. out .println (e .getMesc;age ( ) ) ;

18. 1 19. !

-DOMInternalValidator.java 1. ~azkage com. ysreddy. xml. dom. valldator;

' 2 . 3. lrn,port lava. io. IOExcept on; 4. 5. ii~~port j avax. xml .parsers. DccumentBuilder; 6 . import j a v a x . xml. parsers. UocumentBuiiderFactory; 7. impart jauax.xml.parsers.ParserConfigurationException; 8. 9. import org . ~ 3 c . dom. Document; 10. import org.xm1.sax.SAXException; 11. 12. import com.ysreddy.xml.errorhandler.SimpleErrorHand1er; 13.

- 1 4 . publlc class DOMInternalValidator {

15. public static void main(String[] args) throws SAXException, - -

16. ParserConfjgurationException, IOException {

-17. DocumentBuilderFactory factory = DocumentBuilderFac~ory.newIristance(); 18. factory. setvalidating (true) ;

DocumentBuilder builder = ~actory.newDocumentBuilder(); builder.setErrorHandler(new SimpleErrorHandler()); Document document= builder.parse(

DOMInternalValidator.class.getClassLoader() .getResourceAsStream( llcom/ysreddy/xml/config/message.xmll'));

System.out.println( " . . . . . . . . . . ' I ) ;

DOMExternalValidator . j ava - . package com.ysreddy.xml.dom.validator; 2. 3 . import j ava . io . IOExcept ion; 4.

-5. import javax.xml.parsers.DocumentBuilder; 6. import javax.xml.parsers.DocumentBuilderFactory; 7. lmport javax.xm1.parsers.ParserConfigurationException; 3. import javax.xm1.transform.Source; 9. import javax.xm1.transform.stream.StreamSource; .O. import javax.xml.validation.SchemaFactory:

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

Page 20 http://javabynataraj.blogspot.com 79 of 99.

Page 80: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

, - - - -~ -. ~ - - . ~ - . ~..~.

XML By Mr. SekharReddv - I

.. I . - i~.p:rt org . w3c. dom. Document; . ,. ,

i-;!~per+ org. :xml. sax. inputSourc?; i ,T,T ..,.. .- r '- arg. :>;rnl. sax. SAXException; ~. I

imcez.rr_ zorr.. ysreddy. xml. errorhandler. SimpleErrorHandler; 1 , '

iri~p:~rl: .:om. ysreddy. xml. j axp. validator. JAXPValidator; 1

public static'.roid main(String[] args) throws SAXException, P a r s e r C o n f i g u r a t i o n E ~ : c e p t i o r ! , IOException {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(fa1se); factory. setNamespaceP.i.iare (true) ;

SchemaFactory schemaFactory = I I

SchemaFactor>i. newInstance ("http: //www. w3. org/2OOl/XMLScheina") ; I

factory.setSchema(schemaFactory.n~~?Schema( new Source [ ] {new Streamsource (

i i DOMExternalValidator.class.getClassLoader() . getResourre~-s~tream ( ~ ' ~ o ~ n / y - s r e d d y / x m 1 / c o n f i g / m e s s a g e . xsdr') ) 1 ) ) ; \~ i ,

\,

DocumentBuilder builder = factory.newDocumentBuilder(); I I

Document document = builder.parse(new Inputsource( ~~~~xterr~al~alidator.class.getClassLoader() .get~esource~s~tream("com/ysreddy/xml/config/message

System.out.println(" . . . . . . . . . "); 1

1 I I

SAXInternalValidator.java 1. package com.ysreddy.xml.sax.val~dator; \- 1

i 2. 3. lmport ]ava.lo.IOException; \ I

4. I

5. import ~avax.xm1.parsers.ParserConf~gurat~onException; I 6. import javax.xml.parsers.SAXParser; I

7. import ]avax.xrnl.parsers.SAXParserFactory; \

8. I 9. import org.xml.sax.InputSource; 10. import org.xm1.sax.SAXException; I

I 11. Import org.xml.sax.XMLReader; 12. 13. import com.ysreddy.xml.errorhandler.SimpleErrorHand1er;

. I i

14. 15. public class SAXInternalValidator [

1 7

16. public static void main(Strlng[] args) throws IOException, SAXException, 17. ~arser~onf igurat ionException {

18.

I 19. SAXParserFactory factory = SAXParserFactory.newInstance(); 20. factory. setvalidating (true) ;

\ l 21. factory.setNamespaceAware(true); - I - -

Naresh i Technologies, Opp. Satyam Theatre, ~meerbet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company I

Page 21 -- http://javabynataraj.blogspot.com 80 of 99.

Page 81: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML - 1 By Mr. SeltharReddy !

SAXParser parser = factory.newSAXParser(); parser. setpropsrt y (

"tttp://java.sun.com/xml/jaxp/propertiss/schemaLanguage", "http://www.w3.org/2001/XMLSchema");

XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(nei~ SimpleErrorHandler()); reader. parse (new Inputsource (

SAXInternaiVal~dator.class.getClassLoader() .getResourceAsStream(1'~om/ysreddy/xml/conf~g/message.xml'1)));

System. out .prlntln ( " . . . . . . . . . ") ;

I SAXExternalValidator.iava 1. package com.~~sreddy.xml.sax.validator;

/ 2. 1 3. import j ava . lo. IOExcept ion; I 4. 1 5. lmport javax.xm1.parsers.ParserConfigurationException; I 6. lmport J avax. xml .parsers. S~~parser; I

7. lmport javax.xm1.parsers.SAXParserFactory; L . lmport ~avax.xm~.trans~orm.Source; 9. lmport ]avax.xml.transform.sfieam.StreamSource; 10. lmport javax.xml.validation.SchemaFactory;

- 11. 12. lmport org.xml.sax.InputSource; 13. import org.xml.sax.SAXException; 14. lmport org.xml.sax.XMLReader; 15. 16. lmport com.ysreddy.xml.dom.val~dator.DOMExternalValidator; 17. lnport com.ysreddy.xml.errorhandler.SimpleErrorHand1er; 18. 19. publlc class SAXExternalValidator {

20. public static vold main(Stringl1 args) throws SAXException, IOException, 21. ParserConfigurationException { 22. 23. SAXParserFactory factory = SAXParserFacizory.newInstance(); 24. factory.setValidating(fa1se); 25. factory.setNamespaceAware(true); 26. 27. SchemaFactory schemaFactory =

28. SchemaFactory.newInstance("http://www.w3.org/2O@l/XMLSchemaf'); 29. 30. factory.setSchema(schemaFactory.newSchema( 31. new Source [ ] {new 32. StreamSource(SAXExternalValidator.class.getClassLoader()

- -33. .getResourceAsStream("com/ysreddy/xn~l/config/message.xsd11) ) 1 ) ) ;

34. 35. SAXParser parser = factory.newSAXParser(); 36. 37. XMLReader reader = parser.getXMLReader(); 38. / / reader.setErrorHandler(new SimpleErrorHandler()); 39. reader.parse(new Inputsource(

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842

- - - An IS0 9001 : 2000 Certified Company Page 22

http://javabynataraj.blogspot.com 81 of 99.

Page 82: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- .

By Mr. SekharReddv 11

. i

JAXPValidator .iava .' . i i

1. package com.ysreddy.xml.jaxp.~.ialid-itor; , \ I I

2. 3. import j ava . io. IOExcept ion;

. ~ .., i 4 . import java. io. Inputstream; I i 5 . I

I 6. import javax.xm1.XMLConstants; ,I !

7. import javax.xm1.transform.Source; i I 8. ir.port javax.xml.transform.stream.StreamSource; I

i 9. import javax.xml.validation.Schema; 10. import javax.xml.validation.Sch~maFactory; 11. import javax.xml.validation.Validator;

, :I ' .'i

12. 13. import org.xml.sax.SAXException; / I 14. '..- ,,

15. public class JAXPValidator ( I

, I

16. public static void rnain(String[] args) throws SAXException, IOException { \ - ! 17. 1 18. / / I. Lookup a factory for the W3C XML Schema language r. 19.. SchemaFactory factory = 1 20. SchernaFactory . newInstance onstant st ants. W3C - XML - SCHEMA - NS URI ) ; i

- 1

21. 1 22. / / 2. Compile the schema. , .- <

23. Inputstream xsdInputStream = JAXPValidator.class.getClassLoader() 24. .getResourceAsStream("~om/ysreddy/xml/config/messaqe.xsd~'); 25. Source xsdsource = new StreamSource(xsd1nputStream); , .

26. Schema schema = factory.newSchema(xsdSource); I

. . 27. 28. / / 3. Get a validator from the schema. ' 1

I

29. Validator validator = schema.newValidator(); i ,

30. 31. / / 4. Parse the document you want to check.' 32. Inputstream xmlInputStream = JAXPValidator.class.getClassLoader0

1. 33. .getResourceAsStream("com/ysreddy/xml/config/messa~e.xml"); 34. Source xmlsource = new StreamSource(xml1np~tStream); (x

- 35. I

I /

36. / / 5. Check the document \

37. try { I 38. validator.validate(xmlSource); 39. System.out .println(" Given is valid. " ) ;

40. I 41. catch (SAXException ex) {

42. System.out.println("Given is not valid because " ) ; I

I 43. System.out.println(ex.getMessage()); 7

44. I I 45. !

46. 1 47. } I

(, -1

- r I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 - -

An IS0 9001 : 2000 Certified Company I

Page 23-- http://javabynataraj.blogspot.com 82 of 99.

Page 83: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML Bv Mr. ~ekharReddv-~~-1

0.) Which one is better, SAX or DOM ? In what cases, we prefer SAXParser and Il)OMl'arser?

130th SAX and DOM parscr havc thcir advantages and disadvan~ages. Which one is better

, should depends on the chal-acteristics of your application.

StAX slr:ll\jes S A X and De.3P.l pr-oblerris by p r - o v i d i ng rnor-e c s n t r - c l l of Xb1L yzrsing to the pr-ugr-arnnier-, in p a r t i c u l a r - by

I e x p c i s i n g a sirr- [PIP i t e r - a t o r - - b a s e d API and an u n d e r - l y i n g I str-ear-n o f events. r..lethods such as next() and hasNexJ(3 I I

alluw an a p p l i c a t i r ~ l n developer- t o ask f o r - the nest event, o r - pull t h e event, r-ather- than h a n d l e the event i n a cgI Ibpck. StA-y a l s o enables t h e programmer to stop pr-ocessing the d o c 1 - 1 r n e r i t a t any tirne. skip atlead t o secticins of t h e dc)currient. and get subsections o f the d o c u rrient.

4.) What is JAXB?

P JAXB stands for "Java Architecture for XML Binding" -

r JAXB is a Java standard that defines how Java objects are converted tolfrom XlVlL

Example binding frameworks:

Caster, Glue, JAXB, XMhBeans, XStream, Liquid ... etc.

Q.) Why JAXB?

P Prograrr~mers don't have to deal with XNIL directly

P JAXB parser is faster than SAX parser

P JAXB also provides random accses like DOM P It provides compiler that compiles XML schema to Java classes

P JAXB is high-level language while JAXP/SAX/DOM are asserrl bly

language for XML document Management. -

-2.)How to use JAXB to access XML document?

;tep 1: Generate the Java source files by submitting the XNIL Schen~a to the binding compiler(XJC)

Naresh xchnologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

-- An IS0 9001 : 2000 Certified Company Page 24.

http://javabynataraj.blogspot.com 83 of 99.

Page 84: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

C:/> xjc (-options) schema

C:/> xjc -p <package-name> -d <destination> schema

Step 2: Compile the Java source code.

Step 3 : Pcrfoonn Mars hallIUl~mars ha1 operations

,TAX13 architecture

P V * --- Bin ding L~ysrrxi

Binding Life Cycle

I I'

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company I

-- Page T5- -

http://javabynataraj.blogspot.com 84 of 99.

Page 85: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- .. -~ . . . . . . ~ ~. . . . .~ ~ ~ - .. .. ,

XML By Mr. SekharReddv i

rt . - marshal (va!idate]

JAXB compile time steps(one time operation1

Develop or obtain XML schema - - Generate the java source files by compiling the XML schema through the binding compiler

Develop JAXB client application (with the javax;xrr~l.bind JAXB interfaces)

Compile the Java source codes

I -- I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- -- -- An I S 0 9001 : 2000 Certified Company

- Page 26--:

http://javabynataraj.blogspot.com 85 of 99.

Page 86: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

--.-. ~. -- ~ - . - . - . ~ ~ ~ ~ ~ ~ ~.. .. - - ~ ~ . ~

XML By Mr. SekharReddv - I

JAXB Runtime Steps

With the classes and the binding framework, write Java applications that

UnmarshaIIing the data from an XML I

Access and modify the data. ! Optionally validate the against XML schema.

Marshal in-memory data t o a ,new XML document

Steps t o work wi th JAXB(Usinp XJC o f iwsdp-2.0 1

Step 1: Create "java project" I

Step 2: Create one source folder with name "resources" !

Step 3: Place company.xsd file in "resources" folder

Step 4: Create binding classes by running XJC compiler as follovds

(set the path to java version "1.5.0-22", set path t o "C:\Sun\wsdp-2.0\axb\binM )

Step 5: Place the required jar files in the classpath to work wi th JAXB

Step 6: Perform Marshall, UnMarsall operations using JAXB API.

NOTE: If we are using JDK 6 and more version, we no need t o add any jar files. Because JDK itself has -I JAXB implementation. 1

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

An I S 0 9001 : 2000 Certified Company I Page 27 -

http://javabynataraj.blogspot.com 86 of 99.

Page 87: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- . - . . - -- . . . - - -. - . - - - - . . . . - -- - -. . pp -- - .... . . . . .. - . .- .. -. - - - . . .- - - . . .

XML By Mr. SekharReddy I

Steps to work with JAXB(Using XJC of JDK 6.0)

Step 1: Create "java project'

I Step 2: Create one source folder with name "resources"

I ' Step 3: Place cornpany.xsd file in "resources" folder

I Step 4: Set the path to jdk 6.0

I set path=C:\Program Files\Java\jdkl.6.0-18\bin;%path%

Step 5: Perform Marshall, UnMarsall operations using JAXB API.

- , d

r 'eJc jaxb 4 :,-* src

A c ~ t ~ i . y ~ . r ~ ~ l ~ ~ y . x n i l , _ ~ a ~ b ~ c c . r n f ; a t ~ y ~ ~ ~ ~ ~ e ~

[& Adclr~ssTy pe,; ava

& CampanyType,java jl' Etnplyd--T., . r e .ape.java

ObjectFactorjt,java

@ package-lnfu,java

A ;% rccni.yl--r~ddy.xml,ja:rb.marshalI /& Cot?ipanl;Marshall,jaua

ccttnpany.xsd

,'& JRE 5ysteni Library i;k,l,,,,Ci--.2E

\ & Rdercnced L lb rar i~~ - - r p rnylib

&A act~vation.jar

gpj laxh-apidar

jaxb-impl,jar

oig,apache.renriceniixX~pecs4stax-api-l .- l~l~~jai

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

Page 28 http://javabynataraj.blogspot.com 87 of 99.

Page 88: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML Bv Mr. SekharReddv -

companv.xsd ' 7. <?xml version="l.O" encoding="UTF-a"?> 1 8. c:xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 1 9. elementFormDefault="qualif ied" attributeFormDefault="unqualif ied" I 10. targetNamespace="http://ysreddy.comhl/~axb/company/types" j 11. xmlns:c="http://ysreddy.com/xml/jaxb/company/types"> 12. 13. <xs:element name="companyU type="c:companyTypeW / >

1 14. 15. <xs:complexType name="companyType">

I 16. <xs:sequence> 17. <xs:element name="employee" type="c:employeeType" 18. minOccurs="l" max0ccurs="unbounded" / > 19. </xs:sequence>

corn panv.xml 1. <?xml version="l.OV enccding="UTF-8"?> 2. <c:company xmlns:c="http://ysreddy.com/xml/jaxb/company/types"

I 3 . xrnlns:xsi="http://www.w3.org/2001/XMLScherna-in~tan~e" 4. xs~:schemaLocation="http://ysreddy.com/xml/jaxb/company/type~

i 5. f~le:///E:/Y.S.Reddy/XML/xsd-examples/xsd/company.xsd"> 6. <c:employee>

! 7. <c:eno>1001</c:eno> 1

I 8. <c:name>ysreddy</c:name> I 9. <c:salary>2498.98</c:salary> 10. <c:address> 11. <c:hno>l-2A/2</c:hno>

I 12. <c:city>Hyd</c:city> 13. <c:p~ncode>5000082</c:pincode> - . I 14. </c:address> 15. </c: employee> 1 16. 17. <c:employee> I 18. <c:eno>1002</c:eno> 19. <c:name>ys</c:name> I I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

An IS0 9001 : 2000 Certified Company I - -

Page 29 - http://javabynataraj.blogspot.com 88 of 99.

Page 89: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

~ - ~ .~ -..

XM L - I Bv Mr. SekharReddv I

CompanvMarshall.iava 1. package com.ysreddy.xml.~axb.marshall; 2. 3. lmport javax.xml.blnd.JAXBContext; 4. Import ]avax.xml.bind.JAXBExceptlon; 5. 1mporL ]avax.xml.bind.Marshaller; 6. 7. lmport com.ysreddy.xm1.jaxb.company.types.AddressType; 8. import com.ysreddy.xml.jaxb.company.types.CompanyType; 3 . lmport com.ysreddy.xml.jaxb.company.types.EmployeeType; 10. 11. public class CompanyMarshall {

12. public static void main(Strlng[] args) throws JAXBException {

13. JAXBContext context = JAXBContext.newInstance( -

14. "com.ysreddy.xml.jaxb.company.types"); 15. Marshaller marshaller = context.createMarshaller();

-: 6. marshaller.setProperty(Marshaller.JAXB - FORMATTED - OUTPUT, true);

CompanyType companyType = new CompanyType();

EmployeeType el = new EmployeeTypeO; EmployeeType e2 = new EmployeeTypeO;

AddressType a1 = new AddressTypeO; al.setHno("l/2A"); al.setCit-y ("hyd") ; al.setPincode(l234);

el.setEno(10001); el.setName("abc"); el. set,Salary (4500.00) ; el. setAddress (al) ;

e2.setEno(10002); e2 .setName ("xyz") ; e2.setSalary(4569.00); e2.setAddress(al);

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

-- An IS0 9001 : 2000 Certified Company

Page 30 http://javabynataraj.blogspot.com 89 of 99.

Page 90: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

, -- ~ ~~ ...~. .~ .. ~ . . ~ ~

1 XML By Mr. SekharReddv -. r

45. 1 . - . , 46. j

1 - ',. , 1 CompanyUnmarshall.iava I

! 1 1. package com.ysreddy.xml.jaxb.marshall; .\ i I 2. I

1 3. imp-" jara.io.InputStream; -. '

: 4. I - 8

! 1 5. import. j avar,. xrnl . XMLConstants; I

6. import jauax.xm1.bind.JAXBContext; 1 : , ;

I I . , 8

: 7. i-inpcrt j avax. xrnl .bind. JAXBElement; / 8. import jas.ax.xrnl.bind.JAXBException; , ! ,

1 9. j rriport javax.xm1. bind. Unmarshaller; I

1 10. import javax. xrnl .transform. Source; I

! 11. import j avax . xrnl . transform. stream. Streamsource; -, 8

i ! 12. import javax.xml.validation.Schema; i

13. import javax.xml.validation.SchemaFactory; , I

1 14. j 1 15. import org.xml.sax.SAXException; , , .. , !

16. , . \ ..I

I 17. import com. ysreddy. xml. jaxb. company. types. CompanyType; 1 j 'i 18. import com.ysreddy.xmi.jaxb.company.types.Employee?'ype; ' I

19. i 20. public class CompanyUnMarshall { -

21. public static void main (String [ ] args) throws SAXException, JAXBException { " ! 1

22. SchemaFactory factory = SchemaFactory.newInstance( i 23. XMLConstants.W3C XML SCHEMA NS URI); -, - - - -

24. Inputstream inputstream = ~om~an~~n~arshall.class.getClassLoader() I

25 : . getResourceAsStream ( ll~ompany. xsd") ; i ., . '

26. Source source = new StreamSource(inputStream); - . I

27. Schema schema = factory.newSchema(source); /

i '

28. JAXBContext context = JAXBContext.newInstance( I 29. "corn. ysreddy. xml . jaxb. company. types") ; .- 1

i 30. Unmarshaller unmarshal= context.createUnmarshaller(); I 31. unmarshal.setSchema(schema);

# ~

I 32. JAXBElement<CompanyTypez element= (JAXBElement<CompanyType>) . .

33. unmarshal.~nmarshal(~om~ar~~~n~arshall.class.getClassLoader() 34.

i .getResourceAsStream('lcompany.xm~")); ' '

35. CompanyType companyType = element.getValue(); 1

i

36. System.out.println("Employees information...."); I

37. for(Emp1oyeeType employeeType: companyType.getEmployee()){ 38. System.out.println("\nENO : "temployeeType.getEno()); ' ! 39. System. out .println ("NAME : "+employeeType. getName ( ) ) ; t

40. Sy~tem.out.println('~SALARY : "+employeeType.getSalary()); ! ,/

i 41. System.out.println("HNO : ntemployeeType.getAddress().getHno()); 42. System.out.println("C1TY : "templ~yeeType.~et~ddress().~et~it~()); 43. System. out. println ("PINCODE : "

, i 44. +employeeType.getAddressO.getPincodeO); 45. 1 - I 46. }

<

47. } , I

\ I I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company I

-- I

Page 31 -- http://javabynataraj.blogspot.com 90 of 99.

Page 91: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

X M L !

JAXB uses annotations to indicate the central elements.

Annotation Description

, @XmIRootElement(namespace = Define the root element for a XML tree "namespace")

I

@XmlType(propOrder = { "field2", Allows to define the order in which the fields are written ~n the XML file j , "fieldl",. . })

I I

@XmlElement(name = "neuName") Define the XML element which will be used. Only need to be used if the ' neuNeu is different then the JavaBeans Name 1

The general steps in the JAXB data binding process are: -

1. Generate classes. An XML schema is used as input to the JAXB binding compiler to generate

-JAXB classes based on that schema.

3. Compile classes. All of the generated classes, source files, and application code must be

compiled.

3 . Unmarshal. XML documents written according to the constraints in the source schema are

~nmarshalled by the JAXB binding framework.

4 . Generate content tree. The unmarshalling process generates a content tree of data objects

instantiated from the generated JAXB classes; this content tree represents the structure and content

~f the source XML documents.

. Validate (optional). The unmarshalling process optionally involves validation of the source XiVlL

docunients before generating the content tree.

6. Process the content. The client application can modify the XML data represented by the Java

~ontent tree by means of interfaces generated by the binding compiler.

'. Marshal. The processed content tree is marshalled out to one or more XML output documents.

The content may be validated before marshalling.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

. -- - -- -. . -- - -- -- - -. - - - An IS0 9001 : 2000 Certified Company

-- - Page 3 2 -

http://javabynataraj.blogspot.com 91 of 99.

Page 92: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- EE a8ed

1 . hueduo3 PJ!J!lJJ3 0002 : '1006 OSI u'd

ZP~PELEZ ' g g g g ~ ~ ~ ~ - o ~ o :qd 'peqe~aph~ '~ad~aaurv ' a ~ i e a y l ureh le~ .ddo 'sa!8o(ou y3al ! ysaJeN

I I

I -

I

1 . aas plnoys noA .anu!luo3 o i I xaN ~3!13

1 : aTOSUO3- ~ X ~ . ~ ~ ~ ~ - S M O ~ U ~ M - O - Z - ~ ~ S M C <\:3

uo!ido alosuo3 8u!sn au!l puewwo3 ay l w o ~ j dasM eAer ayl Ileisul

-10 I .llelsu! 03 uounq uny uo 73!13 pue uo3! -1allelsu! a y i uo I

1313 alqnop pays!u!g s! 8u!peolu~op Jayv 'Jallelsu! daSM eAey ay l s! axa 9 ~ S ~ - S ~ ~ ~ O P U ~ M - O - Z - ~ P S M C allg a y l :Z dais

http://javabynataraj.blogspot.com 92 of 99.

Page 93: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML By Mr. ~ e k h a r ~ e d d v

Welcome to the Installshield Wizard for Java(TM) Web Services Developer Pack 2.0

The Install:?liielrl :?".'i;rartl viill Install .!a:;a(TM) \Web Senices Develnper Pack 2.11 o n !;ol.tt coml:nl.ttcr. Tn cutit lt l~.~e, I:~-ILIII.-.P blest.

.IdvaikT:TF!l) '6/',!'elj !Sanll:-e::, nevelopet Park 2 O :;I.II-~ M~cros!;.;terns, I tic P~ttp ji~a\<a.,:.l.r n.co t-n(.,ii!el~sel~;~ L ec. i \ i , ieI~ser~~~ ce8panI:. t i t r t~l

Stet, 3: Select APPROVE and click Next to see

Step 4: Accept default values or Click Browser button to select JDK5.0 or higher version and click Next. you should see

Naresh i Technologies, Opp. Satyam Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company

- Page 34- - - - '

http://javabynataraj.blogspot.com 93 of 99.

Page 94: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

..~ - ---- . ... -. - . - -- ~ . ~ 7

XML By Mr. SekharReddv . i

Step 5: Select "No Web Container" option and click Next button

- -

Step 6: Leave the Installation Directory on the default and click Next. You should see i

I r . - . * b . r r

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company I

Page 35 - http://javabynataraj.blogspot.com 94 of 99.

Page 95: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

XML Bv Mr. SekharReddv

Step 7:Click Next. You should see

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I I

. An I S 0 9001 : 2000 Certified Company I

Pagc 3Fi-- http://javabynataraj.blogspot.com 95 of 99.

Page 96: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

Step 9:Click Next to accept the defaults. If you use a proxy on your network to access this machine (not likely for localhostl. vou should tvDe in a ~ ~ r o ~ r i a t e values in the fields. You should see

I I -

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- -- - - An I S 0 9001 : 2000 Certified Company I

Page 37- - http://javabynataraj.blogspot.com 96 of 99.

Page 97: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- - -- - - -- - . -. - - ---- ~ . -- - -- - - .> --

XM I~ . Bv Mr. SelcharReddv

5tep 10:Click Next. You should see

I,.,.. 'TI, ' ,. t 4 ! 'i,'\iet:, :3eivices C~evelol:~er F'ac.k 2.111 \;:;ill be installed in the fu l l i~wing location:

,t!m!~l 1-1 It I I-! i ~ - 1 1 1 ~i,w:ir 1c1 i t jtt I VI-! :-,

.J.s.::.-:,':fS '-.:,'e 1.5 i o 1-1 1 <I EA C.la;!a P,F' I it:, r :.: l.IL '!::fe b E: e rvl i e;:, F .3 .st I n i n . et ';?'e er:j i o 1 ,111 1 !:: u 1-1 .J:jv.i Str ea 1-1-1 I np Xlul L Fa r.2 er' '*..;ersiiln I 0 E!: :::f!!lL C, I!:I ith I Sigr-I ,2t1.1rv ',..!t:r S~I:I t i .1 .(:I. I : 1rr)I I.. ;:(n~:j '!:if[! t l Ser\iir:c s $;eel.. rl ti: ".Ver s i 111 t-I 2 .I:! EAZ .J.%:::R '(Vet sjhn ::: 13 EA i,la\;a Arch~terture ii:lr :ClvIL Blr~cllr~g! .J,a.:<.F'iler.~iotl 1 .3.1-1~1 [.lai;a API f13r XklL Ploi.e:;singj .

.J.fi)?R Ver::.ion 1 .l:l.fi-l:rl EA (.Ja;:,a .&PI fnrXML F'egi:stries)

.J.&:;:.-FFC. 'a.jeersior 1 . 1 .3-_01 EP. [.J:y,(a .+PI for XIdL- t:~a.:ed RF'C:) :::A:?,J ',fi.rrior 1 . 3 E,"i (:;i;.&P ,.+?.itt) .:4.ttact)n-lerrts .Z,PI i~:~r.lava)

ii:fr a total 51-o

5 L.1 kll:

-;ten 1l:Cl ick Next. You should see

- I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

An IS0 9001 : 2000 Certified Company I

-- . - -. . - -- -- - I Page 3n

http://javabynataraj.blogspot.com 97 of 99.

Page 98: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

. -- - ~. .---.-~~---.-------~----~~--.p-~p------- ~ ~~ .

XML By Mr. SekharReddv I

i Step 12:Click Ne I

1 I The ln::tallShield Wizard has z;?~cce:s:;fi.rlly it-l':talle~:J Ja?a(Tkl) 'd;'8jel'g Sewices Dr,ijeloper

F'ac1;: 3.0. Choose P4ed tn continue the w,izard. 1

I

!

i

I

I

I

1 i

I ! I

S t e ~ 13:Click Next. You should see

Please read the information below.

For standalone ,lava(TMj applications to work with the Java(TIv1) Web Setvices Developer Pack 2.0, the JAXP classes built into JDi< 1.5.x rnust be overridden. Overriding these classes is not nacessarq in order to run the Web container or the samples , s ince the provided scripts set "java.endorsed.dirsn.

For JDI.: 1.5.x users, set the jwa.endorsed.dirs system proper31 to:

C:l~~.rn!jwsdp-2.Ol~axpllib;C:lSun1j~,~~sdp-22Olja~plIib~.end~rs~d

Iternatively, create the directory:

~J.&V.~.-HOME~i.jrellil3leticIorsecl

and then copy the ti les in the folinwing directories tn the newly created directoly.

C:lS1.1n~w?.clp-2.Oljarp~.lit~ C:lSun!j?wsdp-2.0~axplliblendorsed

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Com~anv I

http://javabynataraj.blogspot.com 98 of 99.

Page 99: XML,WebServices AJAX - WordPress.com i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 .I I An ISO 9001 : 2000 Certified Company I .....

- - -- . - - - -- - - . - - - - - - ppp------ ----- - - - -

X M L Bv Mr. SekharReddv

! I

Step 14: Uncheck Register check box, click Next. You should see I

li?ol.l .~.;-.;ol.~l~:l like to 1:lartlc is1 ate ~n ~:~rc~?;idit~ y ieedbal: I;: to help g u i ~ j e the fi.ltl.lre ~:I lrert ian o f thls ~ ~ t o d ? r c t , ~:~lr. ,r~so .? i~ l~?r : t th~:! rcg~stlat i i l rr o l ~ t ~ o n t ~ e l o w .

'v' F: c. g l.:tcr ,-:;iltl-~ ,J.-\;.rr(Tld:~ :::.ic b !Sc. I-->,I I: r-: ; 0 eve lo pct F'ac lr 2 O

' Steo 15:Clicl< on Finish to exit the wizard.

You have now successfully installed JWSDP (despite the error message).

Step 16: Append the below path to "PATH" system variable. "C:\Sun\wsdp-2.O\axb\binM

I I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 . i An IS0 9001 : 2000 Certified Company

-- ---A

Page 40 http://javabynataraj.blogspot.com 99 of 99.