Tải bản đầy đủ (.pdf) (464 trang)

Addison wesley XML schema complete reference sep 2002 ISBN 0672323745

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.59 MB, 464 trang )

26.1SystemArchitecture
Mostdistributedarchitecturesdiscussthreetiersinthe
developmentofWeb-basedapplications,buttheWebServer
tiershouldreallybethoughtofasaseparatelayer.Infact,as
wemovecloserandclosertoWebservicesthislayermightbe
replacedaltogether.Therefore,thelayersmodeledfortheCRSS
are:
Clienttier
WebServertier
Applicationtier
Databasetier
Let'slookateachtierandthetechnologiesusedtoday.The
ClienttiertypicallyconsistsofHTMLandJavaScriptfor
computersandWirelessMarkupLanguage(WML)forPDAs.Itis
possibletoembedmanyothercontrols(Shockwave,applets,
ActiveX),butwewillexcludetheseplug-intechnologiesfrom
ourapplication.
Thesimplestwaytomodeltheapplicationistostartwithhighlevelarchitecturaldiagramsandthenmodelthetiersoneata
time.
ThearchitectureshowninFigure26.1hasbeenusedinmany
applicationsforquiteafewyearsnow.Infact,thesuccessof
thisarchitecturehasacceleratedtheacceptanceandemergence
ofXMLstandards.
Figure26.1.n-Tierarchitecture.


YoumightwonderwhyXMLSchemaandtheotherXML
conceptsshouldbeintroducedtothemixillustratedinFigure
26.1.Wecertainlyhaveenoughacronymswithoutintroducing
alltheX-basedones.YoushouldnotstarttousealltheseX
technologieswithoutagoodjustification.Properlyjustifyingthe


useofXML-basedtechnologieswillseemsimpleifyouhave
alreadybeendealingwithsomeofthefollowingissues:
HTMLbrowsersdonotcomplywithrigidstandards.This
mightnotbeastunningrevelationtoanyWebdeveloper
whohasbeenupallnightsortingoutaNetscapeversus
InternetExplorerissue.UseXMLwithXSLTtoproducewellformedHTML—orbetteryet,XHTML.
TheWebServertierinFigure26.1hasmanycompeting
technologies.Learningallofthemisdifficult.Theyareall
tryingtodothesamething:acceptuserinputsasHTTP
messagesandformattheoutputresultsasHTMLorWML.
ManyapplicationshavemisusedtheWebserverlayerand
placedfartoomuchvalidationandbusinesslogicinit.
Maintainingtheseprojectsisextremelydifficult.The
technologiesaresimplifieddramaticallyifyouswitchto
XML-basedtechnologiesanduseXMLschemastoperform
thevalidation.
TheComponenttieriscertainlythemostinteresting.You


havethenever-endingdebateaboutJavaversusanything
else.Whatisfrequentlylostinthisdebateisthereal
purposeofthistier,whichistoprovidebusinesslogic.
Businesslogicisbasedondata,andXMListailor-madefor
manipulatingdata.ByusingXML,youcansimplifyyour
componentsbypassingXMLnodesbackandforth.Each
nodecanuseanXMLschemaforitstestcase.This
eliminatestheneedtowritesoftwaretotestsoftware—a
classicCatch-22.IfyouaskWebdevelopershowtheytest
anapplication,they'relikelytosaytheyopenNetscapeand
InternetExplorerandverifythattheapplicationworks.

Couldyouimaginetestinganewaircraftwingbyinstalling
itonaplaneandtakingitupforaflight?Ifitworksonce,
willitworkeverytime?Willitworkwithallrevisions?
Obviously,muchbettertestmethodologyisrequired.
TheDatabasetierisamovingtargetrightnow.Both
MicrosoftandOraclearerapidlyaddingXMLcapabilitiesto
theirdatabases.ThesecapabilitiesenableyoutouseXML
messagestorequestdatabaseactions,eliminatingallthe
formattingrequiredinanActiveServerPage/ActiveData
Object(ASP/ADO)solutionorcorrespondingJavaServer
Page/JavaDatabaseConnectivity(JSP/JDBC)scenario.
Note
MicrosoftandOraclearenottheonlyvendorsusingXMLintheir
databaseproducts.IBM,Informix,Sybase,andothersare
addingsimilarcapabilities.

OurCampusResourceandScheduleSystem(CRSS)casestudy
usesXMLasitsfoundation,whichisillustratedinFigure26.2.
WhencomparingFigure26.2toFigure26.1,themoststriking


differenceistherelianceonXMLacrossallthetiers.
Figure26.2.n-TierXMLarchitecture.

AsyoucanseefromFigure26.2,XMLtechnologiesdonot
replaceHTML,JavaScript,.NET,Java,orSQL.XMLsimplyis
usedbythesetechnologiestoincreasetheirreliabilityand
robustness.
InthemodelinFigure26.2,XMLschemasareusedintwo
ways:

Defininginterfacesbetweendifferentprocessesortiers
Validatingdata
Figure26.2showsthattheWebtierconvertsanincomingHTTP
requestintoanXMLmessage.Thismessageisvalidatedagainst
anXMLschema.Onceyouhavevaliduserinput,themessageis


senttotheComponenttierwherebusinesslogicisapplied.
DatabaseaccessisalsoaccomplishedwithXMLmessages.
Thechallengeatthedatabaseinterfaceisdifferentthanatthe
userinterface.Youcanensurethatyourcomponentsare
producingvalidXMLinthedesignofthecomponents,butyou
needtomapthedatafromanXMLsourcetoarelational
databaseformatandviceversa.XMLschemascanprovidethe
hierarchicaltorelationalmapping,asyouwillseeabitlater.
Interfacesbetweenallthreetiersaresimplifiedwhenusing
XML.TestingatallinterfacesisaccomplishedusingXML
schemas.Thisabilitytotesttheinterfacesdeclarativelyallows
softwareprojectstobeworkedonbyteamsmoreeasily.
YouwillbegintheCRSSapplicationbymodelingtheClienttier
totheWebServertier.Youwillmodeleachrequirementby
usingUMLsequencediagrams.Thenyouwillconverteachof
thesesequencediagramsintoXMLmessages.Thesemessages
definetheworkflowoftheapplication.
Let'sstartbymodelingthefollowingrequirement:Viewexisting
reservationsonaperresourcebasis.
Obviously,userinputwillberequired.Youneedtosupport
multipledevices,butlet'sstartbyassumingabrowser
interface.Asyouwillseelater,implementingthesupportfor
anyotherWeb-enableddeviceiseasy.Thesequencediagramin

Figure26.3modelsthefirstrequirement.
Figure26.3.ViewResourceReservationsequence
diagram.


YoucanseefromthesequencediagraminFigure26.3that
eachtierismodeledbyaninterface.ThereisaWebinterface
thatcanbeimplementedbyusingActiveServerPages(ASP),
JavaServerPages(JSP),CommonGatewayInterface(CGI),or
anyotherWeb-server-basedframework.TheWebinterface
doesnotdoanysignificantprocessing;itspurposeistosupport
userinteraction.Thisisexactlywhatyouintend.Keepthecode
inASPorJSPtoanabsoluteminimumtoincreasethe
maintainabilityofyourapplications.SimplyapplyinganXML
schemaprovidesuser-inputvalidation.Theparserwillthrow
anyvalidationerrorsintherepackagedXMLdata.
Youhaveenoughinformationatthispointtodecideonthe
contentsoftheXMLmessage.TheXMLmessageusedto
requesttheresourcecalendarviewisshowninListing26.1.
Listing26.1XMLMessagetoGetResourceCalendar

<?xmlversion="1.0"encoding="utf-8"?>
<getResourceCalendar>
<resourcename="bigBuilding">


endDay="16"/>
</resource>
</getResourceCalendar>

Asyoucansee,theprecedingcodeisasimpleXMLmessage
createdintheWebClienttier.YoucanuseanXMLschemato
validatethismessage.Theschemaprovidesthecontractyou
havewiththeinputdevice.Usingthismodelenablesusto
supportWeb-basedclientsorXML-enableddevices.Youcanuse
schemastoopenyourservicetotheInternetbycreatingaWeb
service.
Note
TheabilitytopublishschemasontheInternetsoyourservices
canbemadeavailabletoanyoneisthebasisforWebservices.
WebServicesDescriptionLanguage(WSDL)usesXMLschemas
andhasbeensubmittedasapossiblestandardtotheW3C.
WSDLusesXMLschemastodescribeyourapplicationinterfaces
andinterfacedefinitions.

YouneedtocreatetheXMLschemabyusingtheXMLmessage
createdinListing26.1.Youhaveseveralwaysyoucouldgo
aboutcreatingtheXMLschema.Therearequiteafewtoolsthat
doareasonablejob;however,notoolcanknowyourbusiness
applicationrequirements.Mosttoolsthatautomatically
generateXMLschemasproducesomethingsimilartothe
exampleinListing26.2,producedbyXMLSpy.
Listing26.2XMLSchemaforResourceCalendarMessage

<?xmlversion="1.0"encoding="UTF-8"?>


targetNamespace=
" />xmlns:xsd="

xmlns=
" />elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:elementname="getResourceCalendar">
<xsd:complexType>
<xsd:sequence>
<xsd:elementref="resource"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:elementname="range">
<xsd:complexType>
use="required"/>
use="required"/>
use="required"/>
use="required"/>
</xs:complexType>
</xsd:element>
<xsd:elementname="resource">
<xsd:complexType>
<xsd:sequence>
<xsd:elementref="range"/>
</xsd:sequence>



use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Nowyouhaveaschematovalidateyourinputmessage
against.Youcantestthisschemabyusingaplug-in
(forInternetExplorer
thatletsyousimplyright-clickonafileandselectValidate.You
couldalsouseanyvalidatingXMLparserforthisoperation.
Beforeyoucandoanytesting,however,youhavetoassociate
theXMLsourcewithitscorrespondingschema.Youcandothat
asshowninListing26.3.
Listing26.3SchemaReferenceAddedtoGetResource
CalendarMessage

<?xmlversion="1.0"encoding="utf-8"?>
xmlns=
" />xmlns:xsi="
xsi:schemaLocation=
" /><resourcename="bigBuilding">
endDay="16"/>
</resource>
</getResourceCalendar>
Notethecustomnamespaceonthethirdline.Thisisagood
practicebecausenamespacesprovidescopetoXMLdocuments.
Listing26.2definedthenamespace,andyouuseitwithinXML
documentsthatwillbevalidatedbyschemaswiththesame



namespace.Moreinformationonnamespacescanbefoundin
Chapter3.
TestingtheXMLschemaisverystraightforward.Youcanuse
anyvalidatingparsertoloadthedocument.Ifthedocument
loadswithnoerrors,theXMLmessageisvalidrelativetothe
XMLschema.Naturallywemustmaketheassumptionthatthe
validatingparserdoesnothaveerrors.Therearemanytools
youcanusetoprovidevalidation.Someofthepopulartoolsare
XMLSpybyAltova()
Xerces( />.NETfromMicrosoft( />IBM'sparsers()
Whenjustdoingquicktests,theInternetExplorerplug-inis
convenient.Microsofthasadownloadcallediexmltls.exe
thatcanbefoundbyfollowingthelinksatthe
site.Afterinstallingiexmltls.exe
youcanjustaddthereferencetoourXMLschemaintotheXML
documentandthenopentheXMLdocumentinInternet
Explorer.Right-clickingwithinthedocumentinInternetExplorer
providesamenuitemtovalidate.Let'stestourdocumentusing
thistestrightnow.
PerformingvalidationtestsusingInternetExplorer'splug-inis
simple,asshowninFigure26.4below.Youcanseethatthe
documentisvalid.YoucanmakechangestotheXMLandverify
thattheXMLschemafunctionsasexpected.Youshouldtestall
thepermutationspossible,sofeelfreetoexperiment.
Figure26.4.Validationtest.


Tip
TheSchemaRecommendationisveryrecentandsomeareas

canbeinterpretedindifferentways.Whentestingyour
schemas,youshouldusethevalidatingparserthatwillbeused
inyourproductionenvironment.Testbyusingseveralvalidating
parserstoensurethattheschemadesignisrobust.Checkat
www.w3.orgforadditionaltoolsthattestXMLschema
compliance.

26.1.1ClientTierModelRevisited
TechnicallythereiscertainlynothingwrongwiththeXML
schemageneratedinListing26.2.Infact,thetoolsdoagreat
jobofgettingyoustarted.Unfortunately,that'stoooftenasfar
asanyonegetswiththeXMLschemadesign.ForXMLschemas


toproviderealpowertoyourprojects,youneedtotakeastep
backandthinkaboutallthedatatypesyourclientapplicationis
likelytosend.Youshouldthencreatesimpledatatypesand
includethemasneededtocreateflexibleXMLschemas.This
wayyoubuildsmall,easilytestedelementsandtheir
correspondingschemasandthenaggregatethemasneeded
intoagoverningdocumentschemaonaperdocumentbasis.
Thefollowingsectionshowshowto
Identifyreusabledatatypes
CreatemodularXMLschemas
Testmodularschemas
AggregatethemodulesintoamasterXMLschematoallow
resourcereservations

26.1.1.1XMLSchemaSupportforReusable
Datatypes

Obviouslythequestionishowtomodularizeyourschemasto
provideamoreproductionworthysolution.Fortunately,the
SchemaRecommendationprovidestechniquestoachievethis
modularity.Thethreetechniquesare

include:Usedtoincludeotherschemadocumentsthat
havethesametargetnamespace.

import:Usedtorefertocomponentsfromother
namespaces.

redefine:Similartoincludewiththeadditionaloption


thatyoucanprovidenewdefinitionsforsomeorallofthe
typesintheredefinedschemadocument.
Belowisanexampleoftheincludeelement:

<xsd:includeschemaLocation="mySchemaModule.xsd"/>
Sometimesyouneedtooverrideanelementdefinitioninan
includedschema.Inobjectoriented(OO)programming
environments,youwouldsimplyinheritfromthebaseclassand
overridethebaseclass'simplementationofaspecificmethod.
XMLschemasborrowfromthispopularapproachthroughthe
useofredefineelements.Listing26.4demonstratestheuse
ofredefine.Redefiningschemasisusefulwhenyouare
includinglargelibrariesandneedtochangeoneortwotypes.
Inmanycasesyouwillfinditmoreusefultojustalterthe
schemaratherthanusingredefine.
Listing26.4RedefiningtherangeTypeSimpleType


<xsd:redefineschemaLocation="mySchemaModule.xsd">
<xsd:simpleTypename="rangeType">
<xsd:restrictionbase="xsd:string">
<xsd:maxLength="30"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:redefine>
26.1.1.2IdentifyingReusableDatatypes
YouknowhowXMLSchemaletsyoureuseandredefine
datatypes.Nowyouneedtodeterminewhatreusablesimple
typesyouneed.ModelingeachmessagebyusingtheUML


techniquesdiscussedinthischapteridentifiesyourapplication's
requireddatatypes.Thecompletedesignprocessesrequiredto
properlymodeltheapplicationarebeyondthescopeofthis
book;however,wedoreviewthesequencediagramyouwilluse
tocreatetheXMLschema.
YouusethedesiredreservationrequestXMLmessageto
identifythedatatypesyouwouldliketocreate.Thisapproach
letsusfocusontheXMLSchematechniquesandillustratehow
tocreatereusableXMLschemas.Typically,youstartwiththe
UMLsequencediagramandthencreateasampleXMLmessage
representingthedatarequiredtoaccomplishthetask.The
sequencediagramforreservingaresourceisshowninFigure
26.5.
Figure26.5.CRSSReservationRequestSequence
diagram.


Inarealsystem,thesequencediagramwouldhavefarmore
complexity.ForourCRSSapplication,asimplediagram
illustrateshowthediagramscanassistincreatingXML
schemas.
UsingthesequencediagraminFigure26.5,youcancreatea
sampleXMLmessagethatassistsindeterminingthedata
requiredtosatisfytherequest.ThesampleisinListing26.5.


Listing26.5ReservationRequestXMLMessage

<?xmlversion="1.0"encoding="utf-8"?>
<reservation_request>
start_date="2001-02-23"
start_time="22:30:00"
duration="5"
description="Varsitybasketballpractice"
configuration="basketball"/>
<security>
last="Lamere"
email=""
type="coach"/>
</security>
location="images/linden.gif">
<roomname="Gymnasium"capacity="100">
url="forms/legal.html"/>

url="forms/rental.html"/>
url="forms/costContract.html"/>
email=""
type="administration"/>
</room>
</building>
<workflow>
<requestview="xslt/request.xslt"status="false"/>


status="false"/>
status="false"/>
</workflow>
</reservation_request>
ThereservationrequestshowninFigure26.5canbebroken
downintoseveralimportantsteps.Thereservationelement
containstheinformationauserisgoingtoprovidebyusinga
browserorsomeotherWebinterfacedevice.The'security'
elementisusedtoattachsecurityinformationtotheincoming
message.Theworkflowelementisusedtotrackthestatusof
thereservationrequest.Thebuildingelementcontains
responsedatathatwillbesenttotheuserwithroomcapacity
information,requiredforms,theroom'scontactpersonand
more.Theapplicationwillfillintheuser'ssecurityinformation,

supplytheuserwiththerequiredformstofillin,andkeeptrack
oftheuser'sstatusincompletingtheworkflow.
Let'susethemessageinListing26.6tocreateamatrixof
datatypesandtheconstraintswewouldliketoapply.The
matrixinformationinTable26.1isareasonablestart.
Table26.1.DatatypesandRequiredConstraints
Item ElementType

1

reservation

2



3



4



AttributeType

Base
Datatype

DesiredConstraints


building

string

Enumeratedlistofpossiblebuildings

room

string

Applyaminandmaxsize

start_date

date

Constrainvaluetoavaliddate
format

start_time

time

Constrainvaluetoavalidtime


format

5




6



7

requestor

8



9



10



11

building

12




13

room

14



duration

int

Valuebetween1and23hours
inclusive

configuration string

Enumeratedlistofroom
configurations

first

string

Applyaminandmaxsize(2,24)

last

string


Applyaminandmaxsize(2,24)

email

string

Constraintoe-mailW3C
Recommendations

type

string

Enumeratedlist

id

int

Numberassignedtoeachbuilding

location

anyURI

ConstraintoW3CspecsforURLs

name


string

Sameruleasreservation\room

capacity

int

ConstrainwithminInclusiveand

maxInclusive
15

request

status

boolean

EnumeratedvalueequaltoTRUEor
FALSE

16

approval

status

boolean


Sameasline15

17

viewCalendar status

boolean

Sameasline15

18

viewPending

boolean

Sameasline15

status


YoucanseeinTable26.1thateachXMLmessagehasanumber
ofdatatypesanddesiredconstraints.Severalofthesedatatypes
willbeveryreusableonmanymessages.Specifically,
constraintsonuser'snames,e-mailformatting,date,time,and
statuswillbeusableacrossmanyXMLschemas.Youalways
wanttoachievethehighestreusableratefromyourwork.
DevelopingmanysmallXMLschemasthatcanbetested
independentlyandthenincludedinyourprojectwillhelp
achievethegoalofreusability.


26.1.1.3CreatingXMLSchemaReusable
Datatypes
Youshouldidentifythedatatypesyouthinkwillbereusablein
thisandfutureapplicationsfromthoseinTable26.1.Many
datatypescanbereusedfrequently.
StartbycreatinganXMLSchemasimpletypetomodel
start_date.TheSchemaRecommendationhasadate
datatypeasoneoftheprimitivedatatypes.TheCRSS
applicationneedstoberestrictedtoallowreservationrequests
tobeplacedonlybetween2001and2099.Inaproduction
applicationyoumightnotwanttocreateaY2.1Kproblem,but
youwillintheCRSSapplicationtodemonstrateXMLSchema
restrictions.
Creatingasimpletypetoconstraintheattributedatecanbe
doneasshowninFigure26.2.Noticethatapatternisusedto
constrainthevaluerangeandtheformatthatthedatemustbe
submittedin.Ifyoujustneededtoconstrainthevaluesto
range,theminInclusiveandmaxInclusiveconstraints
couldhavebeenapplied.
Listing26.6CRSSStartDateConstrained


<?xmlversion="1.0"encoding="utf-8"?>
xmlns:xsd="
<xsd:annotation>
<xsd:documentation>
FormatdaterangetoCCYY-MM-DDw/range2001_to200
</xsd:documentation>

</xsd:annotation>
<xsd:simpleTypename="dateType">
<xsd:restrictionbase="xsd:date">
value="([2][0][0][1-9])-((0[1-9])|(1[0-2]))-\d{1,31}
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
DocumentingyourXMLschemasisalwaysagoodidea.The
restrictionelementspecifiesthatthebasedatatypeyouwill
derivefromistheXMLSchemadate.Thenextlinederivesa
newdatetypebyaddingadditionalrestrictions.Youhave
chosentonamethenewlyderivedtype'dateType'.Thenew
dateTypedatatypehasallthepropertiesoftheXMLSchema
datedatatypeandouradditionalrestrictions.
ThepatternvaluemustbeanXMLSchemaregular
expression.Formoreinformation,refertoChapter14.
Nowthatyouhavecreatedasimpledatatype,dateType,the
questionishowtotestit.Onetechniqueistocreateanother
XMLschemawithaverysimplestructureandjustusetheXML
Schemaincludeelementtoreferencethedatatypeyouhave
created.InthetestcaseinListing26.7,atestXMLschemais
createdthathasarootelementnamedrootwithone
additionalelementcalledtest.Thetestelementtakesone
attribute,dateTest,whichusesournewdateType.Listing


26.7isthetestcase.
Listing26.7SchemaforTestingdateType


1.<?xmlversion="1.0"encoding="utf-8"?>
2.3.targetNamespace="
4.examples/CRSS/dateTypeTest.xsd"
5.xmlns="
6.examples/CRSS/dateTypeTest.xsd"
7.xmlns:xsd="
8.<xsd:includeschemaLocation="dateType.xsd"/>
9.<xsd:elementname="root">
<xsd:complexType>
<xsd:sequenceminOccurs="1"maxOccurs="1">
<xsd:elementname="test">
<xsd:complexType>
type="dateType"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
TheincludeelementinListing26.7includesournew
dateTypesimpletype.ThedateTestattributeusesthe
customdatatypethatyoudefined.Youneedtotestthisby
creatingaXMLdocumentthatadherestotheXMLschemain
Listing26.7andthenvalidatingbyusingoneofanynumberof
tools.Forourpurposes,useMicrosoft's.NETFrameworkto
performthetest.IfyoudonothaveVisualStudio.NETthen



usethevalidationplug-inforInternetExplorermentioned
earlier.
UseanytexteditortocreatethecodeshowninListing26.8.
ThislistingreferencesthedateTypeTestschemathatincludes
thedateTypesimpletypecreatedfirst.Thisprovidesavery
simpletesttoverifythatthesimpletypeiscorrect.
Listing26.8XMLTestCasefordateTypeSimpleType

1.<?xmlversion="1.0"encoding="utf-8"?>
2.<rootxmlns=" />3.<testdateTest="2001-02-26"/>
4.</root>
YoucanexperimentwiththeXMLdocumentinListing26.8and
verifythatyournewdateTypeXMLschemaisworking.
ChangingthedateTestattributeinListing26.8to2000-02-26
resultsinanerrorinthe.NETFramework,asshowninFigure
26.6.
Figure26.6.Failedvalidationresult.

Testingtheschemain.NETissimple.Addthelistingsshownin
Listings26.6,26.7,and26.8.Next,openthefilecontaining
Listing26.8.ThenopentheXMLmenuandchooseValidate.
Notethestatusmessagesdisplayedintheoutputpaneofthe
.NETwindows.
Justtobethorough,alsotestthedateTypebyusingXMLSpy.
WithXMLSpy,youcanusewhatevervalidatingparseryou


prefer.UsingXMLSpy,simplyloadyourXMLdocumentand
assignthedesiredschematovalidatewith.XMLSpydisplays
errorsifyourXMLsourceviolatesthegoverningschema'srules,

asshowninFigure26.7.
Figure26.7.FailedvalidationresultwhenusingXMLSpy.

ThefailedresultinFigure26.7isnotduetotheXMLschema
dateformat.The2000-12-31formatworkswellwiththeXML
schemaprimitivedatedatatype.Thepatternyouused
constrainedthedaterangetotheyears2001through2099.
ProperlyrestrictingyourdatatypesbyusingXMLSchemafacets
reducestheamountofvalidationcodetypicallyrequiredbythe
application.
Note
InadditiontoChapter14,agoodsourceforregularexpressions
isBewarethatXMLSchemaregular
expressionsarenotthesameasPerlregularexpressions.A
goodplacetotestregularexpressionsforcompliancewiththe
XMLSchemaversionisDanielPotter'ssiteat
ThissitefeaturesaJava
appletthatcanbeusedtotestyourSchemapatternsonline


interactively.

26.1.1.4ReusableDatatypeReview
Thisisagoodpointtoreviewwhatwe'vedonesofarin
creatingreusabledatatypes.Theprocessisoutlinedbelow:
1. CreateaUMLsequencediagramforaspecificaction.
UsethesequencediagramtocreateasampleXMLmessage.
Determinethedatatypesrequiredtofulfilltheaction
modeledbythesequencediagram.
Identifythereusabledatatypes.

CreateaseparateXMLschemawiththeproperrestrictions
foreachreusabledatatype.
TesteachXMLschemamodule.
AggregateyourtestedXMLschemamodulesintoamaster
fortheactionmodeledbyyoursequencediagram.
TherearemanydifferentwaystorestrictdatabyusingXML
schemas.Youhaveseenseveralexamplesinpreviouschapters
ofthebook.TheCRSSapplicationXMLschemasrestrictthe
databyusingmanyXMLSchematechniques,includingthe
following:

pattern:Entriesmustmatchthepatternspecified


minOccurs:Minimumnumberofrepetitionsallowed
maxOccurs:Maximumnumberofrepetitionsallowed
minLength:Minimumstringlength
enumeration:Listofallowedentries
minInclusive:Minimumintegervalueallowed
maxInclusive:Maximumintegervalueallowed
EachXMLsimpletypewillnotbereviewedindetail.Thefinal
codelistingforourreservationrequestisinListing26.9.Listing
26.9canbeappliedtoListing26.7toprovidevalidationtothe
completedreservationrequest.
Listing26.9XMLSchemaforCompletedReservation
Request

<?xmlversion="1.0"encoding="utf-8"?>
targetNamespace=

"
xmlns="
xmlns:xsd="
<xsd:includeschemaLocation="dateType.xsd"/>
<xsd:includeschemaLocation="buildingType.xsd"/>
<xsd:includeschemaLocation="roomType.xsd"/>
<xsd:includeschemaLocation="configType.xsd"/>
<xsd:includeschemaLocation="durationType.xsd"/>
<xsd:includeschemaLocation="emailType.xsd"/>
<xsd:includeschemaLocation="requestorType.xsd"/>


<xsd:includeschemaLocation="locationType.xsd"/>
<xsd:includeschemaLocation="nameType.xsd"/>
<xsd:includeschemaLocation="urlFormType.xsd"/>
<xsd:elementname="reservation_request">
<xsd:complexType>
<xsd:sequenceminOccurs="1"maxOccurs="1">
maxOccurs="1">
<xsd:complexType>
type="buildingType"/>
type="roomType"/>
use="required"
type="dateType"/>
use="required"

type="xs:time"/>
use="required"
type="durationType"/>
use="required"
type="xs:string"/>
use="required"
type="configType"/>
</xsd:complexType>
</xsd:element>
<xsd:elementname="security">
<xsd:complexType>
<xsd:sequenceminOccurs="1"maxOccurs="1">


×