You are on page 1of 99

XML,WebServices & AJAX

i Course Objective:
3 . Developing an xml document that acts as textual databases and developing java applications that communicate wi th xml
documc:nts, Use XML t o 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 wi thout page refresh(AJAX)
XML %
/
i Q.) What is XML?
I
i
I
XNlL stands for Extensible Markup Language
I
I > XML i s a markup language much like HTML
I " It is also a specification. [ From W3C {World Wide Web Consortium ) ]
I
I I > XML was designed t o describe data.
1
- > XML i s 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. Thci r goal s 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.
- - - . . . . . .................-. . --. -
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 i s used to exchange the information between applications i n 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>Remi nder ( Par t y ) </ s ubj ect >
<body>Donl t 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 i n 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 i n any XML standard. These tags are
-
"invented" by the author of the XML document.
I
I
That i s 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.
XML allows thc author t o define his/her own tags and his/her own document structure.
I
; Q. ) What is an XML document?
I
I :) Any text file t hat is developed wi t h .xml extension is an xrnl document.
Q. ) What is xrnl application?
I 3 Any computer application that works wi t h an xrnl document is nothing but an xrnl application.
I 3 Working wi th XML document means, perform CRUG operations on t he XNIL.
XML Syntax
I
1
I
An example XML document:
I
I
cbody'>Don ' t f o r g e t me 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 >To 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:
Al l 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>Thi s i s a pa r a gr a ph
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
- - -- - -
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.
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.
.:~-!f-:i. + 3at.i=i.2/11/99>
.- . - . 7'.:l'.2:-2</to>
~:fr~m?Jani</from>
i hea: i l ng>Remi nder </ headi ng>
chodl"Don1t forget me this weekend!</body>
'::/not?;>
.-.::.;nl -,~;+rs.ian="l.O"?>
. : not e 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 i n 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 of a new element.
I
-This will generate an XML error:
<rnessage>if salary < 1000 then</message>
I
1.0 a vo~d t h ~ s error, replace t he "<" character with an entity reference:
<messaqe;,if salary &It; 1000 then</message>
, .There are 5 predefined entity references i n XML:
- - -- -- - - - -. -- - - - -- - . - -.- - - - - - -
Il&lt; 1 1 ; -1Fess than
Il I - . .
r> Igreater than
. . . . . . . . . I .. -: 1
11' [apostrophe
--
Note: Only the characters "<" and "&" are strictly illegal i n XML. The greater than character is legal, but i t is a good
habit t o 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.
-. -- .. -- . . . . ~ -. -. -. -------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~ngl e 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) of XNlL specification is said t o be well-
. formed.
I > An XWlL document is said t o be well-formed i f it observes the following rules.
I
! 1. I t must begin wi th 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 cl cmcnt is everything from (including) the ele'ment's start tag t o (including) t he element's end tag.
I I
An element can contain:
1. other elements
2. t ext
3. attributes
... 4. or a mix of all of t he 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 wi th a number or punctuation character
3. Names cannot start with t he 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.
4. Names cannot contain spaces
Any name can be used, no words are reserved.
, Q;)What are t he 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 t o 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 t o be used for something called namespaces.
XM L Attributes
I > XML elements can have attributes, j ust like HTIVIL.
I > Attrrbutes provide additional information about an element.
I > At t r~but es can occur in any order in an XML element.
. ~ c , Attri bute 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
Attri bute values must always be quoted. Either single or double quotes can be used. For a person's
j ender, the person element can be written like thi s:
or like this:
. . . - . . . . - . - .-........-......... . . .
. . . . . . ~i
:person gender= ' female ' >
I .. .............. - -. .- .. - .. - - .-. -. I
I f t he attribute value itself contains double quotes you can use single quotes, like in this example:
. . . ....... . . . . . .- ....... - ..- .- .- - -
,-<gangster name='George "Shotgun" Zieglerl>
...... 1 . ;... . .- .-. ....... .- . - . . .- .- .......
Jr 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.
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 t he 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 t o use attributes or when t o use elements. Attributes are handy i n HTML. I n XML my --'
I
I
advice IS t o 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~l d elements can)
w altributes are more difficult t o 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 dat c 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 i n 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.
,, ;..~ . . . . . . . . . . . . - . ...-.... ~--eL-*-.-----.----
: --.note
- ~
<dat e>?LO/ 01/ 2008</ dat e>
, 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 I S 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 t o elements. These IDS can be used t o identify XML elements i n 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 i d 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.
The tcrrns parent, child, and sibling are used t o describe the relationships between elements. Parent elements have ,
1
ch~l dren. Children on the same level are called siblings (brothers or sisters).
I
. ,
I
Al l elcrncnts can have text content and attributes (j ust like in HTML).
I Example:
Eler-i~lent: Element:
Siblings
Root element:
.:::b~:~okstore,:.
I
Text :
~ a r e t - ~ t ]
i
The i magc 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.
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 t o rules
specified in DTD / XSD, i t 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 i s 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 t wo things t o 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
t o 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 t o XML application.
Naresh . ~echnol o~i es, 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.
I
I
I
1. XNII. application instantiating the parser and specifying the
I
XML file t o 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 t o the XML application is differ from JAXB }
Valid XML document
1 3 XML parser can make data stored in XML document available t o
XML application if and only i f f the XML documents are valid.
I 3 There are t wo approaches for developing valid XML.
o Using DTD
o Using XSD
Q.)What i s 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 12 -
http://javabynataraj.blogspot.com 12 of 99.
- - - - -- -- - - - - - - -- -- - - - - - - -- .- -- --
From a 111 0 po~nt of vrew, all XML documents are made up by the fol l ow~ng bu~l d~ng blocks:
I
El ement s
ALLrrbutes
En 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 "i mg".
i
I
) Examples:
I
-4ttributcs provide extra information about elements.
4ttributcs are always placed inside the opening tag of an element. Attributes always come i n 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 i n XML, like t he less than sign (c) t hat defines the start of an XVIL tag.
Most of you know the HTML entity: "&nbsp;". This "no'-breaking-space" enti ty is used i n HTML t o insert an extra space
in a document. Entities are expanded when a document is parsed by an XML parser.
'The following entities are predefined i n 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.
- . . . . .-.. . . . . .................... . . . . . . . . . . . ,
XML 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.
"&" wi l l 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.
. . - . . . . . , .. . . .
, /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.
. . . ~~ ~ ....-. ~ ... ~ -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) > .
, 01-
!
: 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~l h 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, . . . . . )
exampl e :
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 i n 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 * ( Oor n)
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 S0 9001 : 2000 Certified Company 1
-
Page 16
http://javabynataraj.blogspot.com 16 of 99.
. .. . . - - - . - - . - - - -- - - -- - . . -- - -- - -- - - -- -- - -. - .- . - - - - -- - . - - - - - - -- - - . - - . . - - -- -. -. . .
XML ~ r . ~ e k h a r ~ e d c l ~ i
2xa1npl e
-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 i ri the example above declares that the ch~l d 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 t o 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
An IS0 9001 : 2000 Certi fi ed Company
http://javabynataraj.blogspot.com 17 of 99.
- - -- --- - - - - - ---- --. - - - --
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 t he
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 S0 9001 : 2000 Certified Company
_I
Page 18 -
http://javabynataraj.blogspot.com 18 of 99.
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 I S0 9001 : 2000 Certified Company
Page IT-'
http://javabynataraj.blogspot.com 19 of 99.
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 <! ATTLI ST 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.
. ~ ~ ~ - - --...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,
i n order t o associate a DTD with the XML 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 t o element to be of type "#PCDATA"
! !ELEMENT from defines the from element t o 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 t o 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.
External DTD Declaration
I f the DTD is declared in an external f ~l e, i t should be wrapped in a DOCTYPE definition with the following syntax:
1
<l PQCT' i PI 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:
. ~ .. . .- -- . . . . . -. ..... --
< ! ELEME~ TT note
< ! ELEMENT to ( # PCDATA) >
< ! ELEMENT from (#PCDATA) >
< ! ELEMENT heading ( #PCDATA) >
< ! ELEMENT body ( # PCDATA) >
........... ..........
Note: Internal DTD's are seldom used. Reusability of DTD's across XML documents is not possible wi t h 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 f rom (#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.
<!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)>
-
< ! ATKI ST 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.
<!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 t o 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 t wo 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 of 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.
- .
+ - 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 f or 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 t o validate an XML document.
I I It is a text file wi t h .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.
. .~ . .
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 i s
limited
5. Cannot define our own data types
6. Doesn't support namespaces
3. Rich in data types, So i t i s 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 t he greatest strength of XML Schemas is the support for data t ypes. 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.
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~ont hDay, 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 S0 9001 : 2000 Certified Company
,
p a g e r
http://javabynataraj.blogspot.com 27 of 99.
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.
4.) What is the XSD equivalent for the following XML element?
ML el ement:
. . . .......... .. . .......
$ . -
- - .- -- - - - .- - - - --
<l as t r i ame lang="EM">Smit?i</lastname>
. - .. A -- -- -
XSD defi ni ti on:
: xs: a t t r i b u t e name="l angl ' t ype =" xs : s t r i n g u / >
( <ns : e1.amrnt namr ="l ast name" t ypo="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
!.
; - ~ef au' l t Values for Attributes
I
. -. . - -- - - -. -. . . . . . . , .......
i 1 < X S : a t t r i b u t e name="l ang" t ype=Ifns: s t r i n g " def aul 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="l angl ' t ype="xs: s t r i n g "
/ 11 . . . . .
I
NOTE: By default an attribute i s 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.
XSD Restrictions/Facets I
I
I !
I
Rest r~ct i ons are used t o defi ne acceptable values for XML el ements or at t ri but es. Restrictions on XPIL
,
el ement s are called facets.
I
-, i
I
Restrictions on Values
, The f ol l ow~ng example defines an element called "age" with a restriction.
grcal cr 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 ~ mi t the content of an XML element t o a set of acceptable values, we would use t he enumeration constra~nt. h i
I
The example below defines an element called "car" wi th 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 t he 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.
Restrictions on a Series of Values
,,attcrr~ corlstraint can be used t o l i mi t the content of an XML el ernmt t o define a series of numbers or l etters
i xampl e#l Acceptable value is ONE of t he LOWERCASE l etters f rom a t o 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 i s THREE of t he 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-
l etters from a t o z:
(
Example#3 Acceptable value i s THREE of the LOWERCASE OR UPPERCASE l etters from a t o 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 i s ONE of t he following l etters: x, y, OR 2:
- -
1
Exarnple#5 Acceptable value i s FIVE di gi ts i n a sequence, and each di gi t must be.in a range f rom 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.
. -. . .- ----- -. -- - -
- - -- - - -
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>
Exampl e#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>
Exarnpl e#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>
Exampl e#8 Acceptable value is male OR female:
/
Exar npl e#9 There must be exactly eight characters i n a row and those characters must be lowercase or uppercase
letters from a t o 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 I S0 9001 : 2000 Certified Company
Page 3 2 -
I
http://javabynataraj.blogspot.com 32 of 99.
sium bet^ of Digits
i
Using ::.i:i:sLi' ,l.y.it~ and f r a c t i o n Ui 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 i mp1 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~t h 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 i n 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 S0 9001 : 2000 Certified Company
-
Page 33--
http://javabynataraj.blogspot.com 33 of 99.
This exampl e def ~nes an el ement called "password" wi t h a restri cti on. The val ue must be exactly ei ght
characl ers:
--
I
I
i Restrictions for Datatypes (-1
This exampl e def ~nes another el ement called "password" wi t h a restriction. The val ue must be mi ni mum
fi ve characters and maxi mum ei ght 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 l ei s 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
. t o 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.
--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: Xi dL Schema' s built-in types are atomic, meaning that they cannot be broken down lnto mean~ngf ul 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 S0 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.
Union types are groupings of types, essentially allowing for the value of an element t o be of more than
_ ,
one type. I n the example below, two atomic simple types are derived: Rl -l nni ng Race and Gymnastics.
j
I
A third simple type, Event , is then derived as a union of the previous two. The Ev ent element is of
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 S0 9001 : 2000 Certified Company
- -
Pagc 3
-
http://javabynataraj.blogspot.com 36 of 99.
. ~ ~ . . . .. ~
"I"",C"t.)-..>7,%@e-wFiD
:Complex Types
i
1
I
4) What i s a Complex Element?
, compl ex el ement is an XML el ement t hat contai ns ot her el ement s and/or attri butes.
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 Compl ex t ypes ar e def i ned usi ng <complextype> el ement in t wo 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.
< XS : (! 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 t ype-"xs : i n t e g e r " / >
</ x s : :~(:(III~. , 'rice>
</>;:; : (:ornF) I (!xrl.'ype>
</:.::; : c, I. c!rnci rl L>
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 ~i r~(>>, ' ; (: khn r< /name>
<<,I(](!>% 6</<3g0>
I
I
Approach #2: The "person" element can have a type attri bute that refers t o the name of the complex
type -
<x:; : (? I (:rri(:rll: name-"person" t ype="per sonTypen/ >
<xs : r:omp I cxrl'ype name="personTypef' >
<x S : sc:(qlle.nce>
<xs : el -ement name="namel' t ype="xs : s t r i ng1' / >
<xs : ( ?l cmcnt name="age" t ype="xs : i nt e ge r 1' / >
</x:; : scclucnce>
< / x s : cornp.l.ex'Type>
1 NOTE: Advantage of thi s 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 S0 9001 : 2000 Certified Company
.-
~ a g e 3 -
http://javabynataraj.blogspot.com 38 of 99.
---, her-e ar e Cour kinds of complex elements:
1 . Elements wi t h attri butes
2. Elements wi th sub elements
3. Elements wi t h attri butes and t ext
4 . Elements wi t h sub elements and t ext
Note: Each of these elements may contai n attributes as well!
1.Elements with attributes
,An errl pty complex el ement cannot have contents, only attri butes.
I
i
!
-
. .cVc. ...,. . (:I (:rn(:r1\. r~nmc-"product ">
1.1 <x >i : cornplexType>
< x s : CJ ( . ( . r . i but e 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 t he "product" el ement 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 cs t r i c t i o n base=l 1xs : i n t e g e r n >
1-11
< x s : a t t r i b u t e name-"prodi d" type="xs:positiveInteg~r~~/>
</x:; : r(:sI:ri.ctj.on>
< / x s : c:omplexContenl:>
111 < / X S : complexType>
I
I
I n t he exampl e above, The complexcontent el ement signals t hat we i ntend t o restri ct or extend t he
content model of a complex type, and t he restriction of integer declares one at t ri but e but does not
I i ntroduce any el ement content.
1 Exampl e
i
2.Elements with sub elements
-
i
You can defi ne the "person" el ement i n a schema, l i ke this:
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
I
T; . - . - _ . _ . . . . . . ..
An I S0 9001 :.2000 Certified Company
~ a g m - - '
http://javabynataraj.blogspot.com 39 of 99.
Example
1
1
I
I
' I
I
, 3. El ement s with at t ri but es and text , i I
1 I
I I
, Th~s type contains only simple content (text and attributes), therefore we add a simplecontent el ement
I around the conlent. When using simple content, you must define an extension OR a restriction wi t hl n
; Lhe simplecontent element
I
1 ) NOTE: Use Lhe extension/restriction element t o expand or t o l i mi t 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 S0 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: r cst 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.
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:; : (: Oi i l ~, l ex'l'ypc>
11x : 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 t he ~r st ance document below is an empty element.
I <Homepage URL=" http : //www . marktwain. cornf1 />
/ ' I ndi cators
-
1
We can cont r ol HOW elements are t o be used i n documents wi th 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 I S0 9001 : 2000 Certified Company
--. -- -- - . - - - - --
Page 41--
http://javabynataraj.blogspot.com 41 of 99.
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 t o define the order of the elements. > I
'/
i
I All Indicator
i
t
I
The <al l > indicator specifies t hat t he child elements can appear i n any order, and that each child el ement -
must occur only once:
. . . . - - . . --
<XS : (2 I orn(!nl: name="person">
<>::; : camp I.cxType>
<: x: ; : t 3 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 t he <all> indicator you can set the <minOccurs> indicator t o 0 or 1 and the
<maxOccurs> indicator can onl y be set t o 1 (the crninOccurs> and <maxOccurs> are described later).
Choice Indicator
/ The <choice> indicator specifies t hat 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?r nc\ n I->
- - - p p - - -
Naresh i Technologies, Opp. Satyam Theatre, ~ me e r ~ e t , Hyderibad, Ph: 040-23746666,23734842
An I S0 9001 : 2000 Certified Company
- -. . - - -. - -. . . . . . . . - . . . - ---
Page 48'-
http://javabynataraj.blogspot.com 42 of 99.
3ecgr;ence Indicator
, h e <sequence> indicator specifies that the child elements must appear i n a specific order:
I
. - . . . - -- -- - --- ~ --
x : ? I o r I name-"servletW>
I <x:; : r:onpl crxClype>
<\::i : :j(?(qllCrlce>
I
<xi < : 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 al 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 ma x ~ c c u r s Indicator I
'
7-hc <max~ccur s> indicator specifies the maxi mum 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 t he "child-name" element can occur a mi ni mum of one ti me (the default
/
value for minoccurs is 1) and a maxi mum of ten times i n the "person" element.
I minOccurs Indicator
I
I
I
The <njinOccurs> indicator specifies the mi ni mum 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.
The c:xample above indicates that the "child-name" element can occur a mi ni mum of zero times and a
x
maximum of ten t ~mes i n the "person" element.
-
NOTE: To allow an element t o appear an unlimited number of times, use t he maxOccur s=" unboundedl '
statement. i
-1.
NO'I'i~:: rni nOccurs and maxOccur s can also be applied t o model groups (e.g, xs:sequence) to control !
the 11uniber of times a model group can be repeated.
Group Indicators
I
Group ~ri d~cat ors are used to define related sets of elements.
4
1
Elernent Gr o u p s
ElcrncriL groups are defined wi th the gr oup declaration, like this:
You must def ~ne an all, choice, or sequence element inside the group declaration. The following example
der ~r ~es a group named "persongroup", t hat defines a group of elements that must occur i n 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 name" t ype=" xs : s t r i n g w / >
<<>i:; : ( 2 1 c:rnenL name="l ast name" t ype=" xs : s t r i n g w / >
c,u:; : c; l . or ne~~t n. arne="bi rt hday" t ype=" xs : dat eu/ >
</x:; : :;c(qu.oncc>
< / x s : c~ r.o up>
.......... --
After you have defined a group, you can reference it i n another definition, like this:
<x:; : corny) I c:xType name=" per soni nf o" >
<x:; : : ; o ( ~ I J c ~ ~ ( : ( ~ >
i x s : CJ r o u p re E=" per songr oup" / >
. c x s : c l c ment name=" count r y" t y pe=" x s : s t r i ng" / >
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
I
An I S0 9001 : 2000 Certified Com~anv I
. .
Page 44'
http://javabynataraj.blogspot.com 44 of 99.
Attri bute Groups
I
I
!
I
. ~ t l r ~ b u l c groups are defined wi t h t he attri buteGroup decla'ration, l i ke thi s:
The rollowing example defines an at t ri but e 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>
-- - .- - - - -
Al l er you have defined an at t ri but e group, you can reference it i n another definition, like thi s:
. . . . . . . -. ...
1 <,,c. . : I 1. 1. r i 1 G r o u p name="personattrgroup"> ,
1 <any> Element
The <any> el ement enables us t o ext end t he XML document wi t h elements not specified by t he 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.
<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 <~nyAt t ri but e> element enables us to extend the XML document wi th 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 S0 9001 :a2000 Certified Company
- - - - - ----
Page 44
http://javabynataraj.blogspot.com 46 of 99.
( ' rhi s 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.
. . - - -- - . -... .~ -. -.
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 ,
cl ci l i ei ' l t~: :..s : doc~l m@nt at i r , n andxs : appI nf o, 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 i bu. t e, xs : s . mx11 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 ~pI nf 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 i n 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 l mc!>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.
(
11,:; xri l carrlcs information about an HTML table, and a piece of furniture: i
- . - -.. -. -- - .. - I
l n 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
(
Wh c r ~ using pref~xes i n XML, a so-called namespace for t he 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 . ZO</ f : length>
</ r : I ~: I L) I (:>
I n t he example above, the xml ns attri bute i n t he <table> t ag give the h: and f: prefixes a qualified
I namespace.
-
1
When a namespace is defined for an element, al l child elements wi th the same prefix are associated wi th
thc samc namespace.
I
'
Narncspaces can be declared i n t he elements where they are used or i n the XML root element:
I
i
I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
. - -- --
An I S0 9001 : 2000 Certified Company
~ajjFI-9--
http://javabynataraj.blogspot.com 49 of 99.
1
Note: Thc namespace URI is not used by t he parser to look up information. ..I
I i
1
I
I
!
1 1
/ The put-pose is to gi ve 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 i n 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 i nformati on 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 S0 9001 : 2000 Certified Company
- . . . . . . . . . . . . . .
Page 5:
-
http://javabynataraj.blogspot.com 50 of 99.
-1 j Devel op 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>
. - </ ~~oi t ! >
. . . . . -. . - -- - -. - - --
: : I r a xmlns: xs="http: //widw. w3 .org/200l/XMLSchema"
L-I: ,;, I.il-imespace="http: //www. sekharit . com"
:.i-l! ; . : : ; =. "nt t p: //www. sekharit. co~n"
i: i.:!?:?n l : F' ormDefaul t ="qual i fi ed">
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: I TI ~. ;ersion='ll . Off?>
-
<xs:schema xmlns:xs="http://www.w3.0rg/2001/XMLSchemaff
ta.rgct:Kamespace="http://sekharit.com"
xrnlns=" ht tp: //sekharit . corn"
el er nei - ~t For mDef aul t ="qual 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.
I
----{-efauit namespace
-
I I
~111111s 1 targetNamespace="http://sekhar~t.com"
-
A+&-- t ~ r i bute 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 Us ~ r ~ q 111~1 schemaLocation attribute. Th~s attribute has two values, separated by a space. The first value is t he
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 xml ns="ht t p: / / www. s e k h a r i t . com"
x;r\;:~:s: r i si - "t i t t p: / / www. w3. org/2OOl/XMLSchema-instance"
x::. i : ::;::h~n;aLocation="http: / / www. s e k h a r i t . com not e . xs dW>
- - -
Exmaple I
L
--- .- -
~ml n~: ~~=~' ht t p: / / www. w3. or g/ L001/ XMLSchema" Ij
I
i 1
I I
<t:c>?:ove</to>
<Iroi !~: . ~Jani </ from>
<headi ng>, Remi nder</ headi ng>
< ~ , ~ c : ~ , .% ,, :..O;jri ' t f o r g e t me t h i s weekend ! </ body>
</ not e. >
. ~ . . . . . ..
i
.. .. I
j
,
-. . - -
clcri-icntt-or-mllcfault
. . - - .-
xrL?:7r- --.- h t t p : / / www. 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 i n
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 of the XML schema t o use for that namespace:
el ementF~rmDefaul t=~~qual i fi ed' '
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.
. -
1 1 , ; . : : . 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 t ri t ~ut e name=''schemaLocation"/,
<xs:al tribute name="noNamespaceSchemaLocationlt/~
</xs:sc:horiia>
-
- - - .- - p-
I
I
! An XSD Example
I -
/
l~tlis will dcn~onstrate how t o 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 l ook a t t hi s XML document cal l ed "shi porder.xml "
I 1
< 1:; t) i p l.o>
< I I . c! r n>
(I. i I. 1 o>ll:rnp.i.re Bu r l e s q u e < / t i t l e >
I 1 <no l ~a>Spcci . al Ed i t i o n < / not e >
-
<clu,~riL. i . I +y>l </ quant i i ; y>
<pr 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 your h e a r t < / t i t l e >
1 1 <quariI. i i . y>l </ qua nt i t y>
............ ---
........ .- ............ - .. .- .- - .- 1 !!EF=-x' =
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
LA.. . . . . -. -
An I S0 9001 : 2000 Certified Company
Page 53
http://javabynataraj.blogspot.com 53 of 99.
1-llc X ML document above consists of a root element, "shiporder", that contains a required attribute cal l ed
1
"oi~li'iid". The "shiporder" element contains three different child elements: "orderperson", "shipto" and
,
"11cr11" I he " ~t em" 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 t hat thi s --i
docu~l i enl should be validated against a schema. The line: I
xs, :rioN~mespaceSchemaLocation="shiporder.xsd" specifies WHERE the schema resides (here i t is i n t he .!
s;lii:c_. l ol dcr as "shiporder.xml").
I
Ci-sate ~n XML Schema I
I
Now we want t o 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 si mpl y
I
follow l hc structure i n the XML document and define each element as we find it. We will start wi th t he
I
stari dal d XML declaration followed by the xs:schema element that defines a schema:
I
I
/
In l hc schema above we use the standard namespace (xs), and the URI associated wi t h 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 t o define the "shiporder" element. This element has an attri bute and it contains other
I
/
elernen.ts, therefore we consider it as a complex type. The child elements of t he "shiporder" element i s
1
surrot ~ndcd by a xs:sequence element that defines an ordered sequence of sub elements:
I
(
j
!
Then we have t o define the "orderperson" element as a simple type (because it does not contain any
al l ri bul cs or other elements). The type (xs:string) is prefixed wi th the namespace prefix associated wi th
XML Schema that indicates a predefined schema data type:
I
. . .
<'?xrr: 1 V( ! r : i i or , - " I . 0" encodjng="ISO-8859-1" ?>
. <x: r : :ic:t1<:111a xrnins:xs="http: //www.w3 .org/2OOl/XMLSchema">
. .
. . .
Nexl, we have to define t wo 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 S0 9001 : 2000 Certified Company
pageP!7- .- --
http://javabynataraj.blogspot.com 54 of 99.
. -~
I
. . ; . : : j ; i;ijlii() I (:xr.l'ypt.>
-.:... :5 : : ~ C! CJ 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 mi ni mum 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. Th~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" whi ch
,
nicrll)s LIICIL there can be as many occurrences of the "item" element as the author wishes. Notice t hat t he
i
' nol c" 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 ( ?r n~nL name='lnotell type="xs: string" minOccurs="O" / >
i J
<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 attri bute of the "shiporder" element. Since this i s a required attribute we spec~f y
1 USC- "rcqu~rcd".
I
Note: 1 he al t r ~but e declarations must always come last:
--
I I Y : : 1 . r I e - name="orderidIt t y p e = " ~ ~ : string" use="required"/> 1
- -
I Her e 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 S0 9001 : 2000 Certified Company
Page S T -
http://javabynataraj.blogspot.com 55 of 99.
---
<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 pr cv~ous design method i s very simple, but can be difficult t o read and mai ntai n when documents are
I C O I I ~ ~ ~ C X . -i
I
Ttit. r i cxt desrgn method is based on defining all 'elements and attributes first, and then referring t o t hem
1 usliiy ihc r el 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:; : i 11 (: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" / >
< ! tj c! 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, ~~der abad, ' ~hi 40- 23746666, 23734842
. . . . . .
An I S0 9001 : 2000 Certified Company
-~ -.
Page 5 ' ....
http://javabynataraj.blogspot.com 56 of 99.
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 t o reuse element definitions. This i s
(
doric by namlng the simpleTypes and complexTypes elements, and then poi nt t o them through the type
'
at t r i buLe of the element.
I I-lci-r: i.;,I-hc l hi rd design of the schema file ("shiporder.xsdU):
. -. - -
i 1 I vc! r s 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 I S0 9001 : 2000 Certified Company
Page ST--
http://javabynataraj.blogspot.com 57 of 99.
<,.:.: : 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 rcski cti on element indicates t hat the datatype is derived from a W3C XPlL Schema namespace
dal atypc. So, t he following fragment means t hat the value of the element or attri bute must be a string
VLI ~LJC: '
~ .. .~
I I x ; : t - r i o n
I
.. . - . . .
!
I-hc restriction element is more often used t o apply restrictions to elements. Look at the following lines
f r om 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 S0 9001 : 2000 Certified Company
- - - . . -. . - - -
. .
-
Page 5 -
http://javabynataraj.blogspot.com 58 of 99.
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 t o 9.
i
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
- - - -. - - -
An I S0 9001 : 2000 Certified company
-- p--
pageP5T---
http://javabynataraj.blogspot.com 59 of 99.
XML application development
- I
I
1
4.) What i s an XML application?
r3 A program that works wi th XIVIL document i s known as XML application
I
13 To work with XIVlL documents we need API
!
/ 4.) What i s JAXP?
~3 JAXP stands for Java API for XNlL Processing
G JAXP i s 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 i s called Node
+ DOM i s 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 t o
!
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.
.- -- ..- ... .. . - ~~~ . - . ~ .--.p.......-p-.. -- -- -
~ XbIL By Mr . SekharReddv i
- DOM Architecture
-
:teps t o 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.
.. -. - - - - - - .- .- - - - - -- - -- - - - - - - -- - .
XML By Mr . SeltharKeddy7
1:. i : 1-1-1p 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~ai l . , ; rnl
>I: eti-lpli:~;..~~.::<r-l-~I
4 ..>.. !~i >t-17,~v.~rFl -]rf::. r j ~ - - -.c= -
. -- - 7 8 - 1 : t l l , L[ *- ut e
: j
: ; ........ . . :
o ak,j a-*.:a
i . .... j. .... : . ~. c; ~~[ l ct - l ~~: ~~e~t i ncl , ( t r ai 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 i pI ~y~~, i , yj a
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.
- -. -- - . - - .- - - -- -- - ---
XML Bv Mr . ~ekhar Readv 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 I S0 9001 : 2000 Certified Company
Page 4
http://javabynataraj.blogspot.com 63 of 99.
- - - --- .
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;
: I 1 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 S0 9001 : 2000 Certified Company !
Page 5 ' -
http://javabynataraj.blogspot.com 64 of 99.
,XML By Mr. SekharReddy
1' 3. import java. is. I OE: 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, ~meei pet , Hyderabad, Ph: 040-23746666,23734842
-
An IS0 9001 : 2000 Certified Company
Page 6
http://javabynataraj.blogspot.com 65 of 99.
~ ... ~~. - ~ ... -- - ~ . ~-.. .- - ~~ .
XML By Mr. SekharReddy-\
1
\
I 5 8 . rc-tvrri I!-;-ir,;?r. par se111t (getTexti'alue [empElement, tagIdame) ) ;
. -
1
- .
) 59. 1
60. -.\ :
1
: 61.
\ _ !
private static String getTextValue(E1ement empElement, String tagName) {
1 62. blodeList nl = empElement.getElementsBy4TagName); -- 1
63. Node namzNode = nl . item (9) ; .
i
I
. ,
: 64. Mode textNocie = nameNode.getFirstChild(); I
1 65.
-i I
String nalne = textNode. getNodeValue ( ) ; , I
, ,
I 66. returr! narns;
i
67. 1
I
,
I
I 68.
/ /
1 69.
,
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 74.
- ,
I
75. 1
I I
1 76. . i
1 77. private static Document parseXmlFile() { i. .,!
i
78. Docu~~entBuilderFactory factory = DocumentBuilderFactory.newInstance();
I
79. DocumentBuilder builder;
I ' :
I,.
80. Document document = null; I
81. try { L_l!
82. builder = factory.newDocumentBuilder(); 'i !
1 83. Inputstream is = DomEmployeeReader.class.getClassLoader() .' .. I
84. .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 S0 9001 : 2000 Certified Company
i
----- ---
p a g e l -
http://javabynataraj.blogspot.com 66 of 99.
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.
~ . . -- ~- ~- - ~~ ~ -. . - ~
-- -. . .. .
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.
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.
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.
49. / / 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 S0 9001 : 2000 Certified Company
I
Page 1 -
http://javabynataraj.blogspot.com 70 of 99.
. XML
/ / a~pend a new node to staff
Element age = doc. createElement ("age1') ;
age. appendchild (doc. createTextNode ( " 2 8 " ) ) ;
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 S0 9001 : 2000 Certified Company
Page 12
http://javabynataraj.blogspot.com 71 of 99.
... . . . . . . . . -. . . . . . . .. .-.. .. . . . . - . . . ... ~,
- ,
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 t he difference bet ween 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 S0 9001 : 2000 Certified Company
.-
I
Page 13 -
http://javabynataraj.blogspot.com 72 of 99.
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,' 111u P
Dolzur-rientHandler i mpl ement at i nn
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-1a i 13. I e *. -
, ,. - " " ,. ... , - ,.j -1- j.. .. ...... >,? .:~slg',i;;:gylfgr:: *' -#i$*^ r
1 1 ., ^" ^. ",, , .^ ;, _ _. ;. _ , _. ^ _
3
< i !
Steps t o 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.
XML Mr. Sekhar Redd~ - 1
Step 4: Parsing t he XML document:
-: Fa1 s er . 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.
- ~ ~ ~ ~ ~ ~ ~ ~ . - . - - - . - - . - - 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.
~ ~~ ~ ~ ~- - ~ --
I XML
8. inpor t erg. xml. sax. hel . p=r s. 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. / / Sy s t e m. o u t . p r i n t l n ( " UR1 : " 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.
54. @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. / / Sys t em. out . pr i nt l n( " l oca1Name: " 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.
- - . .- ---. - - ...- .- - .
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~~t i ~. . j zreddy. xt -nI , i axp. ~~aI i dat ~~r
JAXPVaI i dator. j ava
A f & com. yrre~l dy. xn~l . sax. ~. ~~l i dat cr
\
A*.- !J) SMExTern aI'vCaI idator.; a > ~ a
. ,p"j SAMt i t r r nal Val i dat ar . j ava
,me JRE 5ystct-n Li brary 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.
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>ysr@gmail.com</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.
-~ ~. .. ~
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 va 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.
, - - - -~ -. ~ - - . ~ - . ~..~.
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,
Par s er Conf i gur at i onE~: cept i or ! , 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 eddy/ xm1/ conf i g/ mes s age. 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 I S0 9001 : 2000 Certified Company
I
Page 21 --
http://javabynataraj.blogspot.com 80 of 99.
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.
- .
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.
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.
St AX slr:ll\jes SAX 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 yzrsi ng t o t he pr-ugr-arnnier-, i n p a r t i c u l a r - by
I e x p c i s i n g a si rr-[ PI P 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 of event s. 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 or - t he nest event ,
o r - pul l t he event , r-ather- t han h a n d l e t he event i n a
cgI Ibpck. StA-y a l s o enabl es t h e programmer t o st op
pr-ocessing t he doc 1- 1r ner i t at any tirne. skip atlead t o
secticins of t h e dc)currient. and get subsecti ons of t he
d o c u rrient.
4.) What i s 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 t o deal wi th 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 t o Java classes
P JAXB i s high-level language while JAXP/SAX/DOM are asserrl bly
language for XML document Management. -
-2.)How t o use JAXB to access XML document?
;tep 1: Generate the Java source files by submitting the XNIL Schen~a t o the binding
compiler(XJC)
Naresh xchnol ogi es, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
--
An IS0 9001 : 2000 Certified Company
Page 24.
http://javabynataraj.blogspot.com 83 of 99.
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
PV* ---
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.
- .. -~ . . . . . . ~ ~. . . . .~ ~ ~
- .. .. ,
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 S0 9001 : 2000 Certified Company
-
Page 26--:
http://javabynataraj.blogspot.com 85 of 99.
--.-. ~. -- ~ - . - . - . ~ ~ ~ ~ ~ ~ ~.. . . - - ~ ~ . ~
XML By Mr. SekharReddv - I
JAXB Runti me Steps
Wi th t he classes and t he binding framework, wri te Java applications that
UnmarshaIIing t he data from an XML I
Access and modi fy t he data. !
Optionally validate the against XML schema.
Marshal in-memory data t o a ,new XML document
Steps t o wor k wi t h JAXB(Usinp XJC of iwsdp-2.0 1
Step 1: Create "java project"
I
Step 2: Create one source folder wi th name "resources"
!
Step 3: Place company.xsd file in "resources" folder
Step 4: Create binding classes by running XJC compiler as follovds
(set t he path t o java versi on "1.5.0-22", set path t o "C:\Sun\wsdp-2.0\axb\binM )
Step 5: Place t he requi red jar files i n t he classpath t o work wi t h 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 i mpl ementati on. 1
I
Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842
I
An I S0 9001 : 2000 Certified Company
I
Page 27 -
http://javabynataraj.blogspot.com 86 of 99.
- . - . . - -- . . . - - -. - . - - - - . . . . - -- - -. . 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 wi th name "resources"
I
'
Step 3: Place cornpany.xsd file in "resources" folder
I
Step 4: Set the path t o 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 Ll br ar i ~~
- - r p rnylib
&A act~vation.jar
gpj laxh-apidar
jaxb-impl,jar
oi g, apache. renri ceni i xX~pecs4st ax-api -l . -l ~l ~~j ai
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.
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.
~ - ~ .~ -..
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.
, -- ~ ~~ ...~. .~ .. ~ . . ~ ~
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.
XML
!
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
~ont ent 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.
- EE a8ed
1 .
hueduo3 PJ!J!lJJ3 0002 : '1006 OSI u'd
ZP~PELEZ ' g g g g ~ ~ ~ ~ - o ~ o :qd ' peqe~aph~ ' ~ad~aaur v ' a~i eayl ur ehl e~ .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 ayl w o ~ j dasM eAer ayl Ileisul
-10
I .llelsu! 03 uounq uny uo 73!13 pue uo3! -1allelsu! ay i uo
I
1313 alqnop pays!u!g s! 8u! peol u~op Jayv 'Jallelsu! daSM eAey ayl 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.
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 Instal l .!a:;a(TM) \Web Seni ces Devel nper Pack 2.11 on
!;ol.tt coml:nl.ttcr.
Tn cuti tl tl ~.~e, I:~-ILIII.-.P blest.
.IdvaikT:TF!l) '6/',!'elj !Sanll:-e::, nevel opet Par k 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 , i eI ~ser~~~ ce8panI:. t i t rt ~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 S0 9001 : 2000 Certified Company
-
Page 34- - - - '
http://javabynataraj.blogspot.com 93 of 99.
..~ - ---- . ... -. - . -
-- ~ . ~ 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.
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.
Step 9:Click Next t o 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 S0 9001 : 2000 Certified Company
I
Page 37- -
http://javabynataraj.blogspot.com 96 of 99.
- - -- - - -- - . -. - - ---- ~ . -- - -- - - .> --
XM I ~. Bv Mr. SelcharReddv
5tep 10:Cl i ck Next. You should see
I,.,..
'TI, ' , . t 4 ! 'i,'\iet:, :3eivices C~evelol:~er F'ac.k 2.111\;:;ill be i nstal l ed i n the f ul l i ~wi ng 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 , 1111
! : : u 1-1 .J:jv.i Str ea 1-1-1I 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)II.. ;:(n~:j '!:if[! t l Ser\iir:c s $;eel.. rl ti: ".Ver si 111t-I 2 .I:! EAZ
.J.%:::R '(Vet sjhn ::: 13EA i,la\;a Arch~t ert ure ii:lr :ClvIL Bl r~cl l r~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.l ava)
ii:fr a total 51-o
5 L.1 kll:
-;ten 1l : Cl i ck 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.
. -- - ~. .---.-~~---.-------~----~~--.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 Sewi ces 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 standal one ,lava(TMj appl i cati ons to wor k with the Java(TIv1) Web Setvi ces
Devel oper Pack 2.0, the JAXP cl asses bui l t into JDi< 1. 5. x r nust be overri dden.
Overriding t hese cl asses i s not nacessarq i n order to run t he Web contai ner or t he
sampl es, si nce t he provi ded scri pts set "java.endorsed.dirsn.
For JDI.: 1. 5. x user s, set the j wa.endorsed.di rs system proper31 to:
C:l~~.rn!jwsdp-2.Ol~axpllib;C:lSun1j~,~~sdp-22Olja~plIib~.end~rs~d
Iternatively, create t he directory:
~J.&V.~.-HOME~i.jrellil3leticIorsecl
and t hen copy t he ti l es i n the fol i nwi ng directories tn the newl y created di rectol y.
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 S0 9001 : 2000 Certified Com~anv
I
http://javabynataraj.blogspot.com 98 of 99.
- - -- . - - - -- - - . - - - - - - ppp------ ----- - - - -
XML Bv Mr. SekharReddv
!
I
Step 14: Uncheck Register check box, click Next. You should see
I
li?ol.l .~.;-.;ol.~l~:l like t o 1:lartlc is1 ate ~n ~: ~rc~?; i di t ~ y ieedbal: I;: to hel p g u i ~ j e the fi.ltl.lre ~: I l rert i an of
t hl s ~~t o d ? r c t , ~: ~l r. , r~so . ?i ~l ~?r : t th~:! rcg~st l at i i l rr o l ~ t ~ o n t ~el ow.
'v' F: c. g l.:tcr ,-:;iltl-~ ,J.-\;.rr(Tld:~ :::.ic b !Sc. I-->,I I : r-: ; 0 eve l o pct F'ac lr 2 O
'
Steo 15:Clicl< on Finish t o exit the wizard.
You have now successfully installed JWSDP (despite the error message).
Step 16: Append the below path t o "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.

You might also like