ASP Material
ASP Material
ASPVBConditionals
VBScriptConditionalStatements
w3schools.com/asp/asp_conditionals.asp
ConditionalStatements
Conditionalstatementsareusedtoperformdifferentactionsfordifferentdecisions.
InVBScriptwehavefourconditionalstatements:
Ifstatementexecutesasetofcodewhenaconditionistrue
If...Then...Elsestatementselectoneoftwosetsoflinestoexecute
If...Then...ElseIfstatementselectoneofmanysetsoflinestoexecute
SelectCasestatementselectoneofmanysetsoflinestoexecute
If...Then...Else
UsetheIf...Then...Elsestatementifyouwantto
executesomecodeifaconditionistrue
selectoneoftwoblocksofcodetoexecute
Ifyouwanttoexecuteonlyonestatementwhenaconditionistrue,youcanwritethecodeononeline:
Ifi=10Thenresponse.write("Hello")
Thereisno..Else..inthissyntax.Youjusttellthecodetoperformoneactionifaconditionistrue(inthiscaseIf
i=10).
Ifyouwanttoexecutemorethanonestatementwhenaconditionistrue,youmustputeachstatementon
separatelines,andendthestatementwiththekeyword"EndIf":
Ifi=10Then
response.write("Hello")
i=i+1
EndIf
Thereisno..Else..intheexampleaboveeither.Youjusttellthecodetoperformmultipleactionsifthe
conditionistrue.
Ifyouwanttoexecuteastatementifaconditionistrueandexecuteanotherstatementiftheconditionisnot
true,youmustaddthe"Else"keyword:
Example
i=hour(time)
Ifi<10Then
response.write("Goodmorning!")
Else
response.write("Haveaniceday!")
EndIf
http://www.w3schools.com/asp/asp_conditionals.asp
1/2
12/13/2016
ASPVBConditionals
Intheexampleabove,thefirstblockofcodewillbeexecutediftheconditionistrue,andtheotherblockwillbe
executedotherwise(ifiisgreaterthan10).
If...Then...ElseIf
YoucanusetheIf...Then...ElseIfstatementifyouwanttoselectoneofmanyblocksofcodetoexecute:
Example
i=hour(time)
Ifi=10Then
response.write("Juststarted...!")
ElseIfi=11Then
response.write("Hungry!")
ElseIfi=12Then
response.write("Ah,lunchtime!")
ElseIfi=16Then
response.write("Timetogohome!")
Else
response.write("Unknown")
EndIf
SelectCase
Youcanalsousethe"SelectCase"statementifyouwanttoselectoneofmanyblocksofcodetoexecute:
Example
d=weekday(date)
SelectCased
Case1
response.write("SleepySunday")
Case2
response.write("Mondayagain!")
Case3
response.write("JustTuesday!")
Case4
response.write("Wednesday!")
Case5
response.write("Thursday...")
Case6
response.write("FinallyFriday!")
Caseelse
response.write("SuperSaturday!!!!")
EndSelect
Thisishowitworks:Firstwehaveasingleexpression(mostoftenavariable),thatisevaluatedonce.Thevalue
oftheexpressionisthencomparedwiththevaluesforeachCaseinthestructure.Ifthereisamatch,theblock
ofcodeassociatedwiththatCaseisexecuted.
http://www.w3schools.com/asp/asp_conditionals.asp
2/2
12/13/2016
ASPVBLooping
VBScriptLooping
w3schools.com/asp/asp_looping.asp
LoopingStatements
Loopingstatementsareusedtorunthesameblockofcodeaspecifiednumberoftimes.
InVBScriptwehavefourloopingstatements:
For...Nextstatementrunscodeaspecifiednumberoftimes
ForEach...Nextstatementrunscodeforeachiteminacollectionoreachelementofanarray
Do...Loopstatementloopswhileoruntilaconditionistrue
While...WendstatementDonotuseitusetheDo...Loopstatementinstead
For...NextLoop
UsetheFor...Nextstatementtorunablockofcodeaspecifiednumberoftimes.
TheForstatementspecifiesthecountervariable(i),anditsstartandendvalues.TheNextstatementincreases
thecountervariable(i)byone.
Example
<%
Fori=0To5
response.write("Thenumberis"&i&"<br/>")
Next
%>
</body>
</html>
TheStepKeyword
WiththeStepkeyword,youcanincreaseordecreasethecountervariablebythevalueyouspecify.
Intheexamplebelow,thecountervariable(i)isINCREASEDbytwo,eachtimethelooprepeats.
Fori=2To10Step2
somecode
Next
Todecreasethecountervariable,youmustuseanegativeStepvalue.Youmustspecifyanendvaluethatis
lessthanthestartvalue.
Intheexamplebelow,thecountervariable(i)isDECREASEDbytwo,eachtimethelooprepeats.
Fori=10To2Step2
somecode
Next
http://www.w3schools.com/asp/asp_looping.asp
1/3
12/13/2016
ASPVBLooping
ExitaFor...Next
YoucanexitaFor...NextstatementwiththeExitForkeyword.
Fori=1To10
Ifi=5ThenExitFor
somecode
Next
ForEach...NextLoop
AForEach...Nextlooprepeatsablockofcodeforeachiteminacollection,orforeachelementofanarray.
Example
<%
Dimcars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"
ForEachxIncars
response.write(x&"<br/>")
Next
%>
</body>
</html>
Do...Loop
Ifyoudon'tknowhowmanyrepetitionsyouwant,useaDo...Loopstatement.
TheDo...Loopstatementrepeatsablockofcodewhileaconditionistrue,oruntilaconditionbecomestrue.
RepeatCodeWhileaConditionisTrue
YouusetheWhilekeywordtocheckaconditioninaDo...Loopstatement.
DoWhilei>10
somecode
Loop
Ifiequals9,thecodeinsidetheloopabovewillneverbeexecuted.
Do
somecode
LoopWhilei>10
Thecodeinsidethisloopwillbeexecutedatleastonetime,evenifiislessthan10.
RepeatCodeUntilaConditionBecomesTrue
YouusetheUntilkeywordtocheckaconditioninaDo...Loopstatement.
http://www.w3schools.com/asp/asp_looping.asp
2/3
12/13/2016
ASPVBLooping
DoUntili=10
somecode
Loop
Ifiequals10,thecodeinsidetheloopwillneverbeexecuted.
Do
somecode
LoopUntili=10
Thecodeinsidethisloopwillbeexecutedatleastonetime,evenifiisequalto10.
ExitaDo...Loop
YoucanexitaDo...LoopstatementwiththeExitDokeyword.
DoUntili=10
i=i1
Ifi<10ThenExitDo
Loop
Thecodeinsidethisloopwillbeexecutedaslongasiisdifferentfrom10,andaslongasiisgreaterthan10.
http://www.w3schools.com/asp/asp_looping.asp
3/3
12/13/2016
ASPVBProcedures
ASPProcedures
w3schools.com/asp/asp_procedures.asp
InASPyoucancallaJavaScriptprocedurefromaVBScriptandviceversa.
Procedures
TheASPsourcecodecancontainproceduresandfunctions:
Example
<%
subvbproc(num1,num2)
response.write(num1*num2)
endsub
%>
<p>Result:<%callvbproc(3,4)%></p>
</body>
</html>
Insertthe<%@language="language"%>lineabovethe<html>tagtowritetheprocedure/functioninanother
scriptinglanguage:
Example
<%@language="javascript"%>
<%
functionjsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>
<p>Result:<%jsproc(3,4)%></p>
</body>
</html>
DifferencesBetweenVBScriptandJavaScript
http://www.w3schools.com/asp/asp_procedures.asp
1/3
12/13/2016
ASPVBProcedures
WhencallingaVBScriptoraJavaScriptprocedurefromanASPfilewritteninVBScript,youcanusethe"call"
keywordfollowedbytheprocedurename.Ifaprocedurerequiresparameters,theparameterlistmustbe
enclosedinparentheseswhenusingthe"call"keyword.Ifyouomitthe"call"keyword,theparameterlistmust
notbeenclosedinparentheses.Iftheprocedurehasnoparameters,theparenthesesareoptional.
WhencallingaJavaScriptoraVBScriptprocedurefromanASPfilewritteninJavaScript,alwaysuse
parenthesesaftertheprocedurename.
VBScriptProcedures
VBScripthastwokindsprocedures:
Subprocedure
Functionprocedure
VBScriptSubProcedures
ASubprocedure:
isaseriesofstatements,enclosedbytheSubandEndSubstatements
canperformactions,butdoesnotreturnavalue
cantakearguments
Submysub()
somestatements
EndSub
or
Submysub(argument1,argument2)
somestatements
EndSub
Example
Submysub()
response.write("Iwaswrittenbyasubprocedure")
EndSub
VBScriptFunctionProcedures
AFunctionprocedure:
isaseriesofstatements,enclosedbytheFunctionandEndFunctionstatements
canperformactionsandcanreturnavalue
cantakeargumentsthatarepassedtoitbyacallingprocedure
withoutarguments,mustincludeanemptysetofparentheses()
returnsavaluebyassigningavaluetoitsname
http://www.w3schools.com/asp/asp_procedures.asp
2/3
12/13/2016
ASPVBProcedures
Functionmyfunction()
somestatements
myfunction=somevalue
EndFunction
or
Functionmyfunction(argument1,argument2)
somestatements
myfunction=somevalue
EndFunction
Example
functionmyfunction()
myfunction=Date()
endfunction
CallingaProcedure
Thissimplefunctionproceduresiscalledtocalculatethesumoftwoarguments:
Example
Functionmyfunction(a,b)
myfunction=a+b
EndFunction
response.write(myfunction(5,9))
Thefunction"myfunction"willreturnthesumofargument"a"andargument"b".Inthiscase14.
WhenyoucallaprocedureyoucanusetheCallstatement,likethis:
CallMyProc(argument)
Or,youcanomittheCallstatement,likethis:
MyProcargument
http://www.w3schools.com/asp/asp_procedures.asp
3/3
12/13/2016
ASPVBSyntax
ASPSyntax
w3schools.com/asp/asp_syntax.asp
AllourexamplesshowstheASPcodeinred.
ThismakesiteasierforyoutounderstandhowASPworks.
ASPUsesVBScript
ThedefaultscriptinglanguageinASPisVBScript.
Ascriptinglanguageisalightweightprogramminglanguage.
VBScriptisalightversionofMicrosoft'sVisualBasic.
ASPFiles
ASPfilescanbeordinaryHTMLfiles.Inaddition,ASPfilescanalsocontainserverscripts.
Scriptssurroundedby<%and%>areexecutedontheserver.
TheResponse.Write()methodisusedbyASPtowriteoutputtoHTML.
Thefollowingexamplewrites"HelloWorld"intoHTML:
Example
<!DOCTYPEhtml>
<html>
<body>
<%
Response.Write("HelloWorld!")
%>
</body>
</html>
VBScriptiscaseinsensitive.Response.Write()canbewrittenasresponse.write().
UsingJavaScriptinASP
TosetJavaScriptasthescriptinglanguageforawebpageyoumustinsertalanguagespecificationatthetopof
thepage:
Example
<%@language="javascript"%>
<!DOCTYPEhtml>
<html>
<body>
<%
Response.Write("HelloWorld!")
http://www.w3schools.com/asp/asp_syntax.asp
1/2
12/13/2016
ASPVBSyntax
%>
</body>
</html>
MoreExamples
ThereisaneasyshortcuttoResponse.Write().Youcanuseanequalsign(=)instead.
Thefollowingexamplealsowrites"HelloWorld"intoHTML:
Example
<!DOCTYPEhtml>
<html>
<body>
<%
="HelloWorld!"
%>
</body>
</html>
Example
<!DOCTYPEhtml>
<html>
<body>
<%
Response.Write("
YoucanuseHTMLtagstoformatthetext!
")
%>
</body>
</html>
Example
<!DOCTYPEhtml>
<html>
<body>
<%
Response.Write("
Thistextisstyled.
")
%>
</body>
</html>
http://www.w3schools.com/asp/asp_syntax.asp
2/2
12/13/2016
ASPVBVariables
ASPVariables
w3schools.com/asp/asp_variables.asp
Variablesare"containers"forstoringinformation.
VBScriptVariables
Aswithalgebra,VBScriptvariablesareusedtoholdvaluesorexpressions.
Avariablecanhaveashortname,likex,oramoredescriptivename,likecarname.
RulesforVBScriptvariablenames:
Mustbeginwithaletter
Cannotcontainaperiod(.)
Cannotexceed255characters
InVBScript,allvariablesareoftypevariant,thatcanstoredifferenttypesofdata.
Declaring(Creating)VBScriptVariables
CreatingvariablesinVBScriptismostoftenreferredtoas"declaring"variables.
YoucandeclareVBScriptvariableswiththeDim,PublicorthePrivatestatement.Likethis:
Dimx
Dimcarname
Nowyouhavecreatedtwovariables.Thenameofthevariablesare"x"and"carname".
Youcanalsodeclarevariablesbyusingitsnameinascript.Likethis:
carname="Volvo"
Nowyouhavealsocreatedavariable.Thenameofthevariableis"carname".However,thismethodisnota
goodpractice,becauseyoucanmisspellthevariablenamelaterinyourscript,andthatcancausestrange
resultswhenyourscriptisrunning.
Ifyoumisspellforexamplethe"carname"variableto"carnime",thescriptwillautomaticallycreateanew
variablecalled"carnime".Topreventyourscriptfromdoingthis,youcanusetheOptionExplicitstatement.This
statementforcesyoutodeclareallyourvariableswiththedim,publicorprivatestatement.
PuttheOptionExplicitstatementonthetopofyourscript.Likethis:
OptionExplicit
Dimcarname
carname=somevalue
AssigningValuestoVariables
Youassignavaluetoavariablelikethis:
http://www.w3schools.com/asp/asp_variables.asp
1/3
12/13/2016
ASPVBVariables
carname="Volvo"
x=10
Thevariablenameisontheleftsideoftheexpressionandthevalueyouwanttoassigntothevariableisonthe
right.Nowthevariable"carname"hasthevalueof"Volvo",andthevariable"x"hasthevalueof"10".
VBScriptArrayVariables
Anarrayvariableisusedtostoremultiplevaluesinasinglevariable.
Inthefollowingexample,anarraycontaining3elementsisdeclared:
Dimnames(2)
Thenumbershownintheparenthesesis2.Westartatzerosothisarraycontains3elements.Thisisafixed
sizearray.Youassigndatatoeachoftheelementsofthearraylikethis:
names(0)="Tove"
names(1)="Jani"
names(2)="Stale"
Similarly,thedatacanberetrievedfromanyelementusingtheindexoftheparticulararrayelementyouwant.
Likethis:
mother=names(0)
Youcanhaveupto60dimensionsinanarray.Multipledimensionsaredeclaredbyseparatingthenumbersin
theparentheseswithcommas.Herewehaveatwodimensionalarrayconsistingof5rowsand7columns:
Dimtable(4,6)
Assigndatatoatwodimensionalarray:
Example
<%
Dimx(2,2)
x(0,0)="Volvo"
x(0,1)="BMW"
x(0,2)="Ford"
x(1,0)="Apple"
x(1,1)="Orange"
x(1,2)="Banana"
x(2,0)="Coke"
x(2,1)="Pepsi"
x(2,2)="Sprite"
fori=0to2
response.write("<p>")
forj=0to2
response.write(x(i,j)&"<br/>")
next
response.write("</p>")
next
%>
http://www.w3schools.com/asp/asp_variables.asp
2/3
12/13/2016
ASPVBVariables
</body>
</html>
TheLifetimeofVariables
AvariabledeclaredoutsideaprocedurecanbeaccessedandchangedbyanyscriptintheASPfile.
Avariabledeclaredinsideaprocedureiscreatedanddestroyedeverytimetheprocedureisexecuted.No
scriptsoutsidetheprocedurecanaccessorchangethevariable.
TodeclarevariablesaccessibletomorethanoneASPfile,declarethemassessionvariablesorapplication
variables.
SessionVariables
SessionvariablesareusedtostoreinformationaboutONEsingleuser,andareavailabletoallpagesinone
application.Typicallyinformationstoredinsessionvariablesarename,id,andpreferences.
ApplicationVariables
Applicationvariablesarealsoavailabletoallpagesinoneapplication.Applicationvariablesareusedtostore
informationaboutALLusersinonespecificapplication.
http://www.w3schools.com/asp/asp_variables.asp
3/3
12/13/2016
RunningASP
RunASPonYourPC
w3schools.com/asp/asp_install.asp
UsingWebMatrix
WebMatrixisafreetoolthatprovidesaneasywaytobuildASPpages.
WebMatrixcontains:
Webexamplesandtemplates
Supportformanydifferentweblanguages
Awebserver(IISExpress)
Adatabaseserver(SQLServerCompact)
WithWebMatrixyoucanstartwithanemptywebsiteoryoucanbuildontemplates.
WebMatrixalsohasbuiltintoolsfordatabases,websecurity,searchengineoptimization,andwebpublishing.
ToinstallWebMatrix,followthislink:WebMatrix
CreateanEmptyWebSite
FollowthethreesimplestepsbelowtocreateanemptywebsitewithWebMatrix:
SelectaTemplate
EdittheHomePage
RuntheWebSite
Step1:SelectanHTMLTemplate
StartWebMatrix,selectNew.
http://www.w3schools.com/asp/asp_install.asp
1/5
12/13/2016
RunningASP
Fromthetemplategallery,selectEmptySitefromHTMLtemplates.
NamethesiteDemoWeb(oranythingyoulike)andclickNext:
http://www.w3schools.com/asp/asp_install.asp
2/5
12/13/2016
RunningASP
WebMatrixcreatesanewwebsiteanddisplaysaworkspacewindow.
Intheleftpane,selecttheFilesworkspace:
http://www.w3schools.com/asp/asp_install.asp
3/5
12/13/2016
RunningASP
Step2:EdittheHomePage
Toedityourhomepage,doubleclickthefileindex.html.
Putthefollowingcontentintothefile:
index.html
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="utf8"/>
<title>WebPageDemo</title>
</head>
<body>
<h1>MyFirstWebPage</h1>
</body>
</html>
Step3:RunYourWebSite
InWebMatrix,clickRun:
WebMatrixstartsawebserverandrunsthepageinyourdefaultbrowser:
http://www.w3schools.com/asp/asp_install.asp
4/5
12/13/2016
RunningASP
WebMatrixselectsarandomportnumberforyourlocalwebserver.
Intheexampleaboveitisdisplayedas:http://localhost:4676.
CreateanEmptyASPWebSite
Renamethehomepagefromindex.htmltodefault.asp.
NowyouarereadytostartworkingwithASP.
http://www.w3schools.com/asp/asp_install.asp
5/5
12/13/2016
VBScriptFunctions
VBScriptFunctions
w3schools.com/asp/asp_ref_vbscript_functions.asp
ThispagecontainsallthebuiltinVBScriptfunctions.Thepageisdividedintofollowingsections:
Date/TimeFunctions
Function
Description
CDate
ConvertsavaliddateandtimeexpressiontothevariantofsubtypeDate
Date
Returnsthecurrentsystemdate
DateAdd
Returnsadatetowhichaspecifiedtimeintervalhasbeenadded
DateDiff
Returnsthenumberofintervalsbetweentwodates
DatePart
Returnsthespecifiedpartofagivendate
DateSerial
Returnsthedateforaspecifiedyear,month,andday
DateValue
Returnsadate
Day
Returnsanumberthatrepresentsthedayofthemonth(between1and31,inclusive)
FormatDateTime
Returnsanexpressionformattedasadateortime
Hour
Returnsanumberthatrepresentsthehouroftheday(between0and23,inclusive)
IsDate
ReturnsaBooleanvaluethatindicatesiftheevaluatedexpressioncanbeconvertedtoa
date
Minute
Returnsanumberthatrepresentstheminuteofthehour(between0and59,inclusive)
Month
Returnsanumberthatrepresentsthemonthoftheyear(between1and12,inclusive)
MonthName
Returnsthenameofaspecifiedmonth
Now
Returnsthecurrentsystemdateandtime
Second
Returnsanumberthatrepresentsthesecondoftheminute(between0and59,
inclusive)
Time
Returnsthecurrentsystemtime
Timer
Returnsthenumberofsecondssince12:00AM
TimeSerial
Returnsthetimeforaspecifichour,minute,andsecond
http://www.w3schools.com/asp/asp_ref_vbscript_functions.asp
1/5
12/13/2016
VBScriptFunctions
TimeValue
Returnsatime
Weekday
Returnsanumberthatrepresentsthedayoftheweek(between1and7,inclusive)
WeekdayName
Returnstheweekdaynameofaspecifieddayoftheweek
Year
Returnsanumberthatrepresentstheyear
ConversionFunctions
Function
Description
Asc
ConvertsthefirstletterinastringtoANSIcode
CBool
ConvertsanexpressiontoavariantofsubtypeBoolean
CByte
ConvertsanexpressiontoavariantofsubtypeByte
CCur
ConvertsanexpressiontoavariantofsubtypeCurrency
CDate
ConvertsavaliddateandtimeexpressiontothevariantofsubtypeDate
CDbl
ConvertsanexpressiontoavariantofsubtypeDouble
Chr
ConvertsthespecifiedANSIcodetoacharacter
CInt
ConvertsanexpressiontoavariantofsubtypeInteger
CLng
ConvertsanexpressiontoavariantofsubtypeLong
CSng
ConvertsanexpressiontoavariantofsubtypeSingle
CStr
ConvertsanexpressiontoavariantofsubtypeString
Hex
Returnsthehexadecimalvalueofaspecifiednumber
Oct
Returnstheoctalvalueofaspecifiednumber
FormatFunctions
Function
Description
FormatCurrency
Returnsanexpressionformattedasacurrencyvalue
FormatDateTime
Returnsanexpressionformattedasadateortime
FormatNumber
Returnsanexpressionformattedasanumber
FormatPercent
Returnsanexpressionformattedasapercentage
http://www.w3schools.com/asp/asp_ref_vbscript_functions.asp
2/5
12/13/2016
VBScriptFunctions
MathFunctions
Function
Description
Abs
Returnstheabsolutevalueofaspecifiednumber
Atn
Returnsthearctangentofaspecifiednumber
Cos
Returnsthecosineofaspecifiednumber(angle)
Exp
Returnseraisedtoapower
Hex
Returnsthehexadecimalvalueofaspecifiednumber
Int
Returnstheintegerpartofaspecifiednumber
Fix
Returnstheintegerpartofaspecifiednumber
Log
Returnsthenaturallogarithmofaspecifiednumber
Oct
Returnstheoctalvalueofaspecifiednumber
Rnd
Returnsarandomnumberlessthan1butgreaterorequalto0
Sgn
Returnsanintegerthatindicatesthesignofaspecifiednumber
Sin
Returnsthesineofaspecifiednumber(angle)
Sqr
Returnsthesquarerootofaspecifiednumber
Tan
Returnsthetangentofaspecifiednumber(angle)
ArrayFunctions
Function
Description
Array
Returnsavariantcontaininganarray
Filter
Returnsazerobasedarraythatcontainsasubsetofastringarraybasedonafiltercriteria
IsArray
ReturnsaBooleanvaluethatindicateswhetheraspecifiedvariableisanarray
Join
Returnsastringthatconsistsofanumberofsubstringsinanarray
LBound
Returnsthesmallestsubscriptfortheindicateddimensionofanarray
Split
Returnsazerobased,onedimensionalarraythatcontainsaspecifiednumberofsubstrings
UBound
Returnsthelargestsubscriptfortheindicateddimensionofanarray
http://www.w3schools.com/asp/asp_ref_vbscript_functions.asp
3/5
12/13/2016
VBScriptFunctions
StringFunctions
Function
Description
InStr
Returnsthepositionofthefirstoccurrenceofonestringwithinanother.Thesearchbeginsat
thefirstcharacterofthestring
InStrRev
Returnsthepositionofthefirstoccurrenceofonestringwithinanother.Thesearchbeginsat
thelastcharacterofthestring
LCase
Convertsaspecifiedstringtolowercase
Left
Returnsaspecifiednumberofcharactersfromtheleftsideofastring
Len
Returnsthenumberofcharactersinastring
LTrim
Removesspacesontheleftsideofastring
RTrim
Removesspacesontherightsideofastring
Trim
Removesspacesonboththeleftandtherightsideofastring
Mid
Returnsaspecifiednumberofcharactersfromastring
Replace
Replacesaspecifiedpartofastringwithanotherstringaspecifiednumberoftimes
Right
Returnsaspecifiednumberofcharactersfromtherightsideofastring
Space
Returnsastringthatconsistsofaspecifiednumberofspaces
StrComp
Comparestwostringsandreturnsavaluethatrepresentstheresultofthecomparison
String
Returnsastringthatcontainsarepeatingcharacterofaspecifiedlength
StrReverse
Reversesastring
UCase
Convertsaspecifiedstringtouppercase
OtherFunctions
Function
Description
CreateObject
Createsanobjectofaspecifiedtype
Eval
Evaluatesanexpressionandreturnstheresult
IsEmpty
ReturnsaBooleanvaluethatindicateswhetheraspecifiedvariablehasbeen
initializedornot
http://www.w3schools.com/asp/asp_ref_vbscript_functions.asp
4/5
12/13/2016
VBScriptFunctions
IsNull
ReturnsaBooleanvaluethatindicateswhetheraspecifiedexpressioncontains
novaliddata(Null)
IsNumeric
ReturnsaBooleanvaluethatindicateswhetheraspecifiedexpressioncanbe
evaluatedasanumber
IsObject
ReturnsaBooleanvaluethatindicateswhetherthespecifiedexpressionisan
automationobject
RGB
ReturnsanumberthatrepresentsanRGBcolorvalue
Round
Roundsanumber
ScriptEngine
Returnsthescriptinglanguageinuse
ScriptEngineBuildVersion
Returnsthebuildversionnumberofthescriptingengineinuse
ScriptEngineMajorVersion
Returnsthemajorversionnumberofthescriptingengineinuse
ScriptEngineMinorVersion
Returnstheminorversionnumberofthescriptingengineinuse
TypeName
Returnsthesubtypeofaspecifiedvariable
VarType
Returnsavaluethatindicatesthesubtypeofaspecifiedvariable
http://www.w3schools.com/asp/asp_ref_vbscript_functions.asp
5/5
12/13/2016
VBScriptInStrFunction
VBScriptInStrFunction
w3schools.com/asp/func_instr.asp
TheInStrfunctionreturnsthepositionofthefirstoccurrenceofonestringwithinanother.
TheInStrfunctioncanreturnthefollowingvalues:
Ifstring1is""InStrreturns0
Ifstring1isNullInStrreturnsNull
Ifstring2is""InStrreturnsstart
Ifstring2isNullInStrreturnsNull
Ifstring2isnotfoundInStrreturns0
Ifstring2isfoundwithinstring1InStrreturnsthepositionatwhichmatchisfound
Ifstart>Len(string1)InStrreturns0
Tip:AlsolookattheInStrRevfunction
Syntax
InStr([start,]string1,string2[,compare])
Parameter
Description
start
Optional.Specifiesthestartingpositionforeachsearch.Thesearchbeginsatthefirst
characterposition(1)bydefault.Thisparameterisrequiredifcompareisspecified
string1
Required.Thestringtobesearched
string2
Required.Thestringexpressiontosearchfor
compare
Optional.Specifiesthestringcomparisontouse.Defaultis0
Canhaveoneofthefollowingvalues:
0=vbBinaryComparePerformabinarycomparison
1=vbTextComparePerformatextualcomparison
Examples
Example1
<%
txt="Thisisabeautifulday!"
response.write(InStr(txt,"beautiful"))
http://www.w3schools.com/asp/func_instr.asp
1/2
12/13/2016
VBScriptInStrFunction
%>
Theoutputofthecodeabovewillbe:
11
Example2
Findingtheletter"i",usingdifferentstartingpositions:
<%
txt="Thisisabeautifulday!"
response.write(InStr(1,txt,"i")&"<br/>")
response.write(InStr(7,txt,"i")&"<br/>")
%>
Theoutputofthecodeabovewillbe:
3
16
Example3
Findingtheletter"t",withtextual,andbinary,comparison:
<%
txt="Thisisabeautifulday!"
response.write(InStr(1,txt,"t",1)&"<br/>")
response.write(InStr(1,txt,"t",0)&"<br/>")
%>
Theoutputofthecodeabovewillbe:
1
15
http://www.w3schools.com/asp/func_instr.asp
2/2
12/13/2016
VBScriptInStrRevFunction
VBScriptInStrRevFunction
w3schools.com/asp/func_instrrev.asp
TheInStrRevfunctionreturnsthepositionofthefirstoccurrenceofonestringwithinanother.Thesearchbegins
fromtheendofstring,butthepositionreturnedcountsfromthebeginningofthestring.
TheInStrRevfunctioncanreturnthefollowingvalues:
Ifstring1is""InStrRevreturns0
Ifstring1isNullInStrRevreturnsNull
Ifstring2is""InStrRevreturnsstart
Ifstring2isNullInStrRevreturnsNull
Ifstring2isnotfoundInStrRevreturns0
Ifstring2isfoundwithinstring1InStrRevreturnsthepositionatwhichmatchisfound
Ifstart>Len(string1)InStrRevreturns0
Tip:AlsolookattheInStrfunction
Syntax
InStrRev(string1,string2[,start[,compare]])
Parameter
Description
string1
Required.Thestringtobesearched
string2
Required.Thestringexpressiontosearchfor
start
Optional.Specifiesthestartingpositionforeachsearch.Thesearchbeginsatthelast
characterpositionbydefault(1)
compare
Optional.Specifiesthestringcomparisontouse.Defaultis0
Canhaveoneofthefollowingvalues:
0=vbBinaryComparePerformabinarycomparison
1=vbTextComparePerformatextualcomparison
Examples
Example1
<%
txt="Thisisabeautifulday!"
response.write(InStrRev(txt,"beautiful"))
http://www.w3schools.com/asp/func_instrrev.asp
1/2
12/13/2016
VBScriptInStrRevFunction
%>
Theoutputofthecodeabovewillbe:
11
Example2
Findingtheletter"i",usingdifferentstartingpositions:
<%
txt="Thisisabeautifulday!"
response.write(InStrRev(txt,"i",1)&"<br/>")
response.write(InStrRev(txt,"i",7)&"<br/>")
%>
Theoutputofthecodeabovewillbe:
16
6
Example3
Findingtheletter"T",withtextual,andbinary,comparison:
<%
txt="Thisisabeautifulday!"
response.write(InStrRev(txt,"T",1,1)&"<br/>")
response.write(InStrRev(txt,"T",1,0)&"<br/>")
%>
Theoutputofthecodeabovewillbe:
15
1
http://www.w3schools.com/asp/func_instrrev.asp
2/2
12/13/2016
VBScriptLCaseFunction
VBScriptLCaseFunction
w3schools.com/asp/func_lcase.asp
TheLCasefunctionconvertsaspecifiedstringtolowercase.
Tip:AlsolookattheUCasefunction.
Syntax
LCase(string)
Parameter
string
Description
Required.Thestringtobeconvertedtolowercase
Examples
Example1
<%
txt="THISISABEAUTIFULDAY!"
response.write(LCase(txt))
%>
Theoutputofthecodeabovewillbe:
thisisabeautifulday!
Example2
<%
txt="ThisisaBEAUTIFULday!"
response.write(LCase(txt))
%>
Theoutputofthecodeabovewillbe:
thisisabeautifulday!
http://www.w3schools.com/asp/func_lcase.asp
1/1
12/13/2016
VBScriptLeftFunction
VBScriptLeftFunction
w3schools.com/asp/func_left.asp
TheLeftfunctionreturnsaspecifiednumberofcharactersfromtheleftsideofastring.
Tip:UsetheLenfunctiontofindthenumberofcharactersinastring.
Tip:AlsolookattheRightfunction.
Syntax
Left(string,length)
Parameter
Description
string
Required.Thestringtoreturncharactersfrom
length
Required.Specifieshowmanycharacterstoreturn.Ifsetto0,anemptystring("")isreturned.
Ifsettogreaterthanorequaltothelengthofthestring,theentirestringisreturned
Examples
Example1
<%
txt="Thisisabeautifulday!"
response.write(Left(txt,15))
%>
Theoutputofthecodeabovewillbe:
Thisisabeaut
Example2
Returnthewholestring:
<%
txt="Thisisabeautifulday!"
x=Len(txt)
response.write(Left(txt,x))
%>
Theoutputofthecodeabovewillbe:
Thisisabeautifulday!
http://www.w3schools.com/asp/func_left.asp
1/2
12/13/2016
http://www.w3schools.com/asp/func_left.asp
VBScriptLeftFunction
2/2
12/13/2016
VBScriptLenFunction
VBScriptLenFunction
w3schools.com/asp/func_len.asp
TheLenfunctionreturnsthenumberofcharactersinastring.
Syntax
Len(string)
Parameter
string
Description
Astringexpression
Examples
Example1
<%
txt="Thisisabeautifulday!"
response.write(Len(txt))
%>
Theoutputofthecodeabovewillbe:
24
Example2
YoucanalsoputthestringdirectlyintotheLenfunction:
<%
response.write(Len("Thisisabeautifulday!"))
%>
Theoutputofthecodeabovewillbe:
24
http://www.w3schools.com/asp/func_len.asp
1/1
12/13/2016
VBScriptLTrimFunction
VBScriptLTrimFunction
w3schools.com/asp/func_ltrim.asp
TheLTrimfunctionremovesspacesontheleftsideofastring.
Tip:AlsolookattheRTrimandtheTrimfunctions.
Syntax
LTrim(string)
Parameter
string
Description
Required.Astringexpression
Example
Example
<%
fname="Jack"
response.write("Hello"<rim(fname)&"andwelcome.")
%>
Theoutputofthecodeabovewillbe:
HelloJackandwelcome.
http://www.w3schools.com/asp/func_ltrim.asp
1/1
12/13/2016
VBScriptMidFunction
VBScriptMidFunction
w3schools.com/asp/func_mid.asp
TheMidfunctionreturnsaspecifiednumberofcharactersfromastring.
Tip:UsetheLenfunctiontodeterminethenumberofcharactersinastring.
Syntax
Mid(string,start[,length])
Parameter
Description
string
Required.Thestringexpressionfromwhichcharactersarereturned
start
Required.Specifiesthestartingposition.Ifsettogreaterthanthenumberofcharactersin
string,itreturnsanemptystring("")
length
Optional.Thenumberofcharacterstoreturn
Examples
Example1
Return1character,startingatpostion1:
<%
txt="Thisisabeautifulday!"
response.write(Mid(txt,1,1))
%>
Theoutputofthecodeabovewillbe:
T
ShowExample
Example2
Return15characters,startingatpostion1:
<%
txt="Thisisabeautifulday!"
response.write(Mid(txt,1,15))
%>
Theoutputofthecodeabovewillbe:
http://www.w3schools.com/asp/func_mid.asp
1/2
12/13/2016
VBScriptMidFunction
Thisisabeaut
Example3
Returnallcharacters,startingatpostion1:
<%
txt="Thisisabeautifulday!"
response.write(Mid(txt,1))
%>
Theoutputofthecodeabovewillbe:
Thisisabeautifulday!
Example4
Returnallcharacters,startingatpostion12:
<%
txt="Thisisabeautifulday!"
response.write(Mid(txt,12))
%>
Theoutputofthecodeabovewillbe:
eautifulday!
http://www.w3schools.com/asp/func_mid.asp
2/2
12/13/2016
VBScriptReplaceFunction
VBScriptReplaceFunction
w3schools.com/asp/func_replace.asp
TheReplacefunctionreplacesaspecifiedpartofastringwithanotherstringaspecifiednumberoftimes.
Syntax
Replace(string,find,replacewith[,start[,count[,compare]]])
Parameter
Description
string
Required.Thestringtobesearched
find
Required.Thepartofthestringthatwillbereplaced
replacewith
Required.Thereplacementsubstring
start
Optional.Specifiesthestartposition.Defaultis1.Allcharactersbeforethestartpositionwillbe
removed.
count
Optional.Specifiesthenumberofsubstitutionstoperform.
Defaultvalueis1,whichmeansmakeallpossiblesubstitutions
compare
Optional.Specifiesthestringcomparisontouse.Defaultis0
Canhaveoneofthefollowingvalues:
0=vbBinaryComparePerformabinarycomparison
1=vbTextComparePerformatextualcomparison
Examples
Example1
Replacetheword"beautiful"with"fantastic":
<%
txt="Thisisabeautifulday!"
response.write(Replace(txt,"beautiful","fantastic"))
%>
Theoutputofthecodeabovewillbe:
Thisisafantasticday!
ShowExample
http://www.w3schools.com/asp/func_replace.asp
1/3
12/13/2016
VBScriptReplaceFunction
Example2
Replacetheletter"i"with"##":
<%
txt="Thisisabeautifulday!"
response.write(Replace(txt,"i","##"))
%>
Theoutputofthecodeabovewillbe:
Th##s##sabeaut##fulday!
Example3
Replacetheletter"i"with"##",startingatposition15:
Notethatallcharactersbeforeposition15areremoved.
<%
txt="Thisisabeautifulday!"
response.write(Replace(txt,"i","##",15))
%>
Theoutputofthecodeabovewillbe:
t##fulday!
Example4
Replacethe2firstoccurencesoftheletter"i"with"##",startingatposition1:
<%
txt="Thisisabeautifulday!"
response.write(Replace(txt,"i","##",1,2))
%>
Theoutputofthecodeabovewillbe:
Th##s##sabeautifulday!
Example5
Replacetheletter"t"with"##",withtextual,andbinary,comparison:
<%
txt="Thisisabeautifulday!"
response.write(Replace(txt,"t","##",1,1,1)&"<br/>")
http://www.w3schools.com/asp/func_replace.asp
2/3
12/13/2016
VBScriptReplaceFunction
response.write(Replace(txt,"t","##",1,1,0))
%>
Theoutputofthecodeabovewillbe:
##hisisabeau##ifulday!
Thisisabeau##ifulday!
http://www.w3schools.com/asp/func_replace.asp
3/3
12/13/2016
VBScriptRightFunction
VBScriptRightFunction
w3schools.com/asp/func_right.asp
TheRightfunctionreturnsaspecifiednumberofcharactersfromtherightsideofastring.
Tip:UsetheLenfunctiontofindthenumberofcharactersinastring.
Tip:AlsolookattheLeftfunction.
Syntax
Right(string,length)
Parameter
Description
string
Required.Thestringtoreturncharactersfrom
length
Required.Specifieshowmanycharacterstoreturn.Ifsetto0,anemptystring("")isreturned.
Ifsettogreaterthanorequaltothelengthofthestring,theentirestringisreturned
Examples
Example1
<%
txt="Thisisabeautifulday!"
response.write(Right(txt,10))
%>
Theoutputofthecodeabovewillbe:
tifulday!
Example2
Returnthewholestring:
<%
txt="Thisisabeautifulday!"
x=Len(txt)
response.write(Right(txt,x))
%>
Theoutputofthecodeabovewillbe:
Thisisabeautifulday!
http://www.w3schools.com/asp/func_right.asp
1/2
12/13/2016
http://www.w3schools.com/asp/func_right.asp
VBScriptRightFunction
2/2
12/13/2016
VBScriptRTrimFunction
VBScriptRTrimFunction
w3schools.com/asp/func_rtrim.asp
TheRTrimfunctionremovesspacesontherightsideofastring.
Tip:AlsolookattheLTrimandtheTrimfunctions.
Syntax
RTrim(string)
Parameter
string
Description
Required.Astringexpression
Example
Example
<%
fname="Jack"
response.write("Hello"&RTrim(fname)&"andwelcome.")
%>
Theoutputofthecodeabovewillbe:
HelloJackandwelcome.
http://www.w3schools.com/asp/func_rtrim.asp
1/1
12/13/2016
VBScriptSpaceFunction
VBScriptSpaceFunction
w3schools.com/asp/func_space.asp
TheSpacefunctionreturnsastringthatconsistsofaspecifiednumberofspaces.
Syntax
Space(number)
Parameter
number
Description
Required.Thenumberofspacesyouwantinthestring
Example1
Dimtxt
txt=Space(10)
response.write(txt)
Output:
""
http://www.w3schools.com/asp/func_space.asp
1/1
12/13/2016
VBScriptStrCompFunction
VBScriptStrCompFunction
w3schools.com/asp/func_strcomp.asp
TheStrCompfunctioncomparestwostringsandreturnsavaluethatrepresentstheresultofthecomparison.
TheStrCompfunctioncanreturnoneofthefollowingvalues:
1(ifstring1<string2)
0(ifstring1=string2)
1(ifstring1>string2)
Null(ifstring1orstring2isNull)
Syntax
StrComp(string1,string2[,compare])
Parameter
Description
string1
Required.Astringexpression
string2
Required.Astringexpression
compare
Optional.Specifiesthestringcomparisontouse.Defaultis0
Canhaveoneofthefollowingvalues:
0=vbBinaryComparePerformabinarycomparison
1=vbTextComparePerformatextualcomparison
Example1
response.write(StrComp("VBScript","VBScript"))
Output:
0
Example2
response.write(StrComp("VBScript","vbscript"))
Output:
1
Example3
response.write(StrComp("VBScript","vbscript",1))
http://www.w3schools.com/asp/func_strcomp.asp
1/2
12/13/2016
VBScriptStrCompFunction
Output:
0
http://www.w3schools.com/asp/func_strcomp.asp
2/2
12/13/2016
VBScriptStringFunction
VBScriptStringFunction
w3schools.com/asp/func_string.asp
TheStringfunctionreturnsastringthatcontainsarepeatingcharacterofaspecifiedlength.
Syntax
String(number,character)
Parameter
Description
number
Required.Thelengthofthereturnedstring
character
Required.Thecharacterthatwillberepeated
Example1
response.write(String(10,"#"))
Output:
##########
Example2
response.write(String(4,"*"))
Output:
****
Example3
response.write(String(4,42))
Output:
****
Example4
response.write(String(4,"XYZ"))
Output:
XXXX
http://www.w3schools.com/asp/func_string.asp
1/1
12/13/2016
VBScriptStrReverseFunction
VBScriptStrReverseFunction
w3schools.com/asp/func_strreverse.asp
TheStrReversefunctionreversesastring.
Syntax
StrReverse(string)
Parameter
string
Description
Required.Thestringtobereversed
Example1
Dimtxt
txt="Thisisabeautifulday!"
response.write(StrReverse(txt))
Output:
!yadlufituaebasisihT
http://www.w3schools.com/asp/func_strreverse.asp
1/1
12/13/2016
VBScriptTrimFunction
VBScriptTrimFunction
w3schools.com/asp/func_trim.asp
TheTrimfunctionremovesspacesonbothsidesofastring.
Tip:AlsolookattheLTrimandtheRTrimfunctions.
Syntax
Trim(string)
Parameter
string
Description
Required.Astringexpression
Example
Example
<%
fname="Jack"
response.write("Hello"&Trim(fname)&"andwelcome.")
%>
Theoutputofthecodeabovewillbe:
HelloJackandwelcome.
http://www.w3schools.com/asp/func_trim.asp
1/1
12/13/2016
VBScriptUCaseFunction
VBScriptUCaseFunction
w3schools.com/asp/func_ucase.asp
TheUCasefunctionconvertsaspecifiedstringtouppercase.
Tip:AlsolookattheLCasefunction.
Syntax
UCase(string)
Parameter
string
Description
Required.Thestringtobeconvertedtouppercase
Examples
Example1
<%
txt="Thisisabeautifulday!"
response.write(UCase(txt))
%>
Theoutputofthecodeabovewillbe:
THISISABEAUTIFULDAY!
Example2
<%
txt="ThisisaBEAUTIFULday!"
response.write(UCase(txt))
%>
Theoutputofthecodeabovewillbe:
THISISABEAUTIFULDAY!
http://www.w3schools.com/asp/func_ucase.asp
1/1
12/13/2016
XMLAttributes
XMLAttributes
w3schools.com/xml/xml_attributes.asp
XMLelementscanhaveattributes,justlikeHTML.
Attributesaredesignedtocontaindatarelatedtoaspecificelement.
XMLAttributesMustbeQuoted
Attributevaluesmustalwaysbequoted.Eithersingleordoublequotescanbeused.
Foraperson'sgender,the<person>elementcanbewrittenlikethis:
<persongender="female">
orlikethis:
<persongender='female'>
Iftheattributevalueitselfcontainsdoublequotesyoucanusesinglequotes,likeinthisexample:
<gangstername='George"Shotgun"Ziegler'>
oryoucanusecharacterentities:
<gangstername="George"Shotgun"Ziegler">
XMLElementsvs.Attributes
Takealookattheseexamples:
<persongender="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<person>
<gender>female</gender>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
Inthefirstexamplegenderisanattribute.Inthelast,genderisanelement.Bothexamplesprovidethesame
information.
TherearenorulesaboutwhentouseattributesorwhentouseelementsinXML.
MyFavoriteWay
ThefollowingthreeXMLdocumentscontainexactlythesameinformation:
http://www.w3schools.com/xml/xml_attributes.asp
1/3
12/13/2016
XMLAttributes
Adateattributeisusedinthefirstexample:
<notedate="20080110">
<to>Tove</to>
<from>Jani</from>
</note>
A<date>elementisusedinthesecondexample:
<note>
<date>20080110</date>
<to>Tove</to>
<from>Jani</from>
</note>
Anexpanded<date>elementisusedinthethirdexample:(THISISMYFAVORITE):
<note>
<date>
<year>2008</year>
<month>01</month>
<day>10</day>
</date>
<to>Tove</to>
<from>Jani</from>
</note>
AvoidXMLAttributes?
Somethingstoconsiderwhenusingattributesare:
attributescannotcontainmultiplevalues(elementscan)
attributescannotcontaintreestructures(elementscan)
attributesarenoteasilyexpandable(forfuturechanges)
Don'tenduplikethis:
<noteday="10"month="01"year="2008"
to="Tove"from="Jani"heading="Reminder"
body="Don'tforgetmethisweekend!">
</note>
XMLAttributesforMetadata
SometimesIDreferencesareassignedtoelements.TheseIDscanbeusedtoidentifyXMLelementsinmuch
thesamewayastheidattributeinHTML.Thisexampledemonstratesthis:
<messages>
<noteid="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don'tforgetmethisweekend!</body>
</note>
<noteid="502">
http://www.w3schools.com/xml/xml_attributes.asp
2/3
12/13/2016
XMLAttributes
<to>Jani</to>
<from>Tove</from>
<heading>Re:Reminder</heading>
<body>Iwillnot</body>
</note>
</messages>
Theidattributesaboveareforidentifyingthedifferentnotes.Itisnotapartofthenoteitself.
WhatI'mtryingtosayhereisthatmetadata(dataaboutdata)shouldbestoredasattributes,andthedataitself
shouldbestoredaselements.
http://www.w3schools.com/xml/xml_attributes.asp
3/3
12/13/2016
XMLElements
XMLElements
w3schools.com/xml/xml_elements.asp
AnXMLdocumentcontainsXMLElements.
WhatisanXMLElement?
AnXMLelementiseverythingfrom(including)theelement'sstarttagto(including)theelement'sendtag.
<price>29.99</price>
Anelementcancontain:
text
attributes
otherelements
oramixoftheabove
<bookstore>
<bookcategory="children">
<title>HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<bookcategory="web">
<title>LearningXML</title>
<author>ErikT.Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Intheexampleabove:
<title>,<author>,<year>,and<price>havetextcontentbecausetheycontaintext(like29.99).
<bookstore>and<book>haveelementcontents,becausetheycontainelements.
<book>hasanattribute(category="children").
EmptyXMLElements
Anelementwithnocontentissaidtobeempty.
InXML,youcanindicateanemptyelementlikethis:
<element></element>
Youcanalsouseasocalledselfclosingtag:
<element/>
http://www.w3schools.com/xml/xml_elements.asp
1/3
12/13/2016
XMLElements
ThetwoformsproduceidenticalresultsinXMLsoftware(Readers,Parsers,Browsers).
Emptyelementscanhaveattributes.
XMLNamingRules
XMLelementsmustfollowthesenamingrules:
Elementnamesarecasesensitive
Elementnamesmuststartwithaletterorunderscore
Elementnamescannotstartwiththelettersxml(orXML,orXml,etc)
Elementnamescancontainletters,digits,hyphens,underscores,andperiods
Elementnamescannotcontainspaces
Anynamecanbeused,nowordsarereserved(exceptxml).
BestNamingPractices
Createdescriptivenames,likethis:<person>,<firstname>,<lastname>.
Createshortandsimplenames,likethis:<book_title>notlikethis:<the_title_of_the_book>.
Avoid"".Ifyounamesomething"firstname",somesoftwaremaythinkyouwanttosubtract"name"from"first".
Avoid".".Ifyounamesomething"first.name",somesoftwaremaythinkthat"name"isapropertyoftheobject
"first".
Avoid":".Colonsarereservedfornamespaces(morelater).
NonEnglishletterslikeareperfectlylegalinXML,butwatchoutforproblemsifyoursoftwaredoesn't
supportthem.
NamingStyles
TherearenonamingstylesdefinedforXMLelements.Butherearesomecommonlyused:
Style
Example
Description
Lowercase
Allletterslowercase
Uppercase
Alllettersuppercase
Underscore
Underscoreseparateswords
Pascalcase
Uppercasefirstletterineachword
Camelcase
Uppercasefirstletterineachwordexceptthefirst
Ifyouchooseanamingstyle,itisgoodtobeconsistent!
XMLdocumentsoftenhaveacorrespondingdatabase.Acommonpracticeistousethenamingrulesofthe
databasefortheXMLelements.
http://www.w3schools.com/xml/xml_elements.asp
2/3
12/13/2016
XMLElements
CamelcaseisacommonnamingruleinJavaScripts.
XMLElementsareExtensible
XMLelementscanbeextendedtocarrymoreinformation.
LookatthefollowingXMLexample:
<note>
<to>Tove</to>
<from>Jani</from>
<body>Don'tforgetmethisweekend!</body>
</note>
Let'simaginethatwecreatedanapplicationthatextractedthe<to>,<from>,and<body>elementsfromthe
XMLdocumenttoproducethisoutput:
MESSAGE
To:Tove
From:Jani
Don'tforgetmethisweekend!
ImaginethattheauthoroftheXMLdocumentaddedsomeextrainformationtoit:
<note>
<date>20080110</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don'tforgetmethisweekend!</body>
</note>
Shouldtheapplicationbreakorcrash?
No.Theapplicationshouldstillbeabletofindthe<to>,<from>,and<body>elementsintheXMLdocumentand
producethesameoutput.
ThisisoneofthebeautiesofXML.Itcanbeextendedwithoutbreakingapplications.
http://www.w3schools.com/xml/xml_elements.asp
3/3
12/13/2016
XMLIntroduction
IntroductiontoXML
w3schools.com/xml/xml_whatis.asp
XMLisasoftwareandhardwareindependenttoolforstoringandtransportingdata.
WhatisXML?
XMLstandsforeXtensibleMarkupLanguage
XMLisamarkuplanguagemuchlikeHTML
XMLwasdesignedtostoreandtransportdata
XMLwasdesignedtobeselfdescriptive
XMLisaW3CRecommendation
XMLDoesNotDOAnything
Maybeitisalittlehardtounderstand,butXMLdoesnotDOanything.
ThisnoteisanotetoTovefromJani,storedasXML:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don'tforgetmethisweekend!</body>
</note>
TheXMLaboveisquiteselfdescriptive:
Ithassenderinformation.
Ithasreceiverinformation
Ithasaheading
Ithasamessagebody.
Butstill,theXMLabovedoesnotDOanything.XMLisjustinformationwrappedintags.
Someonemustwriteapieceofsoftwaretosend,receive,store,ordisplayit:
Note
To:Tove
From:Jani
Reminder
Don'tforgetmethisweekend!
TheDifferenceBetweenXMLandHTML
http://www.w3schools.com/xml/xml_whatis.asp
1/3
12/13/2016
XMLIntroduction
XMLandHTMLweredesignedwithdifferentgoals:
XMLwasdesignedtocarrydatawithfocusonwhatdatais
HTMLwasdesignedtodisplaydatawithfocusonhowdatalooks
XMLtagsarenotpredefinedlikeHTMLtagsare
XMLDoesNotUsePredefinedTags
TheXMLlanguagehasnopredefinedtags.
Thetagsintheexampleabove(like<to>and<from>)arenotdefinedinanyXMLstandard.Thesetagsare
"invented"bytheauthoroftheXMLdocument.
HTMLworkswithpredefinedtagslike<p>,<h1>,<table>,etc.
WithXML,theauthormustdefineboththetagsandthedocumentstructure.
XMLisExtensible
MostXMLapplicationswillworkasexpectedevenifnewdataisadded(orremoved).
Imagineanapplicationdesignedtodisplaytheoriginalversionofnote.xml(<to><from><heading><data>).
Thenimagineanewerversionofnote.xmlwithadded<date>and<hour>elements,andaremoved<heading>.
ThewayXMLisconstructed,olderversionoftheapplicationcanstillwork:
<note>
<date>20150901</date>
<hour>08:30</hour>
<to>Tove</to>
<from>Jani</from>
<body>Don'tforgetmethisweekend!</body>
</note>
OldVersion
Note
To:Tove
From:Jani
Head:(none)
Don'tforgetmethisweekend!
NewVersion
Note
To:Tove
From:Jani
Date:2015090108:30
http://www.w3schools.com/xml/xml_whatis.asp
2/3
12/13/2016
XMLIntroduction
Don'tforgetmethisweekend!
XMLSimplifiesThings
Itsimplifiesdatasharing
Itsimplifiesdatatransport
Itsimplifiesplatformchanges
Itsimplifiesdataavailability
Manycomputersystemscontaindatainincompatibleformats.Exchangingdatabetweenincompatiblesystems
(orupgradedsystems)isatimeconsumingtaskforwebdevelopers.Largeamountsofdatamustbeconverted,
andincompatibledataisoftenlost.
XMLstoresdatainplaintextformat.Thisprovidesasoftwareandhardwareindependentwayofstoring,
transporting,andsharingdata.
XMLalsomakesiteasiertoexpandorupgradetonewoperatingsystems,newapplications,ornewbrowsers,
withoutlosingdata.
WithXML,datacanbeavailabletoallkindsof"readingmachines"likepeople,computers,voicemachines,news
feeds,etc.
XMLisaW3CRecommendation
XMLbecameaW3CRecommendationasearlyasinFebruary1998.
http://www.w3schools.com/xml/xml_whatis.asp
3/3
12/13/2016
XMLSyntax
XMLSyntaxRules
w3schools.com/xml/xml_syntax.asp
ThesyntaxrulesofXMLareverysimpleandlogical.Therulesareeasytolearn,andeasytouse.
XMLDocumentsMustHaveaRootElement
XMLdocumentsmustcontainonerootelementthatistheparentofallotherelements:
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
Inthisexampleistherootelement:
<?xmlversion="1.0"encoding="UTF8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don'tforgetmethisweekend!</body>
</note>
TheXMLProlog
ThislineiscalledtheXMLprolog:
<?xmlversion="1.0"encoding="UTF8"?>
TheXMLprologisoptional.Ifitexists,itmustcomefirstinthedocument.
XMLdocumentscancontaininternationalcharacters,likeNorwegianorFrench.
Toavoiderrors,youshouldspecifytheencodingused,orsaveyourXMLfilesasUTF8.
UTF8isthedefaultcharacterencodingforXMLdocuments.
CharacterencodingcanbestudiedinourCharacterSetTutorial.
UTF8isalsothedefaultencodingforHTML5,CSS,JavaScript,PHP,andSQL.
AllXMLElementsMustHaveaClosingTag
InHTML,someelementsmightworkwell,evenwithamissingclosingtag:
<p>Thisisaparagraph.
<br>
InXML,itisillegaltoomittheclosingtag.Allelementsmusthaveaclosingtag:
http://www.w3schools.com/xml/xml_syntax.asp
1/4
12/13/2016
XMLSyntax
<p>Thisisaparagraph.</p>
<br/>
TheXMLprologdoesnothaveaclosingtag.
Thisisnotanerror.TheprologisnotapartoftheXMLdocument.
XMLTagsareCaseSensitive
XMLtagsarecasesensitive.Thetag<Letter>isdifferentfromthetag<letter>.
Openingandclosingtagsmustbewrittenwiththesamecase:
<Message>Thisisincorrect</message>
<message>Thisiscorrect</message>
"Openingandclosingtags"areoftenreferredtoas"Startandendtags".Usewhateveryouprefer.Itisexactly
thesamething.
XMLElementsMustbeProperlyNested
InHTML,youmightseeimproperlynestedelements:
<b><i>Thistextisboldanditalic</b></i>
InXML,allelementsmustbeproperlynestedwithineachother:
<b><i>Thistextisboldanditalic</i></b>
Intheexampleabove,"Properlynested"simplymeansthatsincethe<i>elementisopenedinsidethe<b>
element,itmustbeclosedinsidethe<b>element.
XMLAttributeValuesMustbeQuoted
XMLelementscanhaveattributesinname/valuepairsjustlikeinHTML.
InXML,theattributevaluesmustalwaysbequoted.
INCORRECT:
<notedate=12/11/2007>
<to>Tove</to>
<from>Jani</from>
</note>
CORRECT:
<notedate="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
Theerrorinthefirstdocumentisthatthedateattributeinthenoteelementisnotquoted.
EntityReferences
http://www.w3schools.com/xml/xml_syntax.asp
2/4
12/13/2016
XMLSyntax
SomecharactershaveaspecialmeaninginXML.
Ifyouplaceacharacterlike"<"insideanXMLelement,itwillgenerateanerrorbecausetheparserinterpretsit
asthestartofanewelement.
ThiswillgenerateanXMLerror:
<message>salary<1000</message>
Toavoidthiserror,replacethe"<"characterwithanentityreference:
<message>salary<1000</message>
Thereare5predefinedentityreferencesinXML:
<
<
lessthan
>
>
greaterthan
&
&
ampersand
'
'
apostrophe
"
"
quotationmark
Only<and&arestrictlyillegalinXML,butitisagoodhabittoreplace>with>aswell.
CommentsinXML
ThesyntaxforwritingcommentsinXMLissimilartothatofHTML.
<!Thisisacomment>
Twodashesinthemiddleofacommentarenotallowed.
Notallowed:
Strange,butallowed:
WhitespaceisPreservedinXML
XMLdoesnottruncatemultiplewhitespaces(HTMLtruncatesmultiplewhitespacestoonesinglewhitespace):
XML:
HelloTove
HTML:
HelloTove
XMLStoresNewLineasLF
Windowsapplicationsstoreanewlineas:carriagereturnandlinefeed(CR+LF).
UnixandMacOSXusesLF.
OldMacsystemsusesCR.
http://www.w3schools.com/xml/xml_syntax.asp
3/4
12/13/2016
XMLSyntax
XMLstoresanewlineasLF.
WellFormedXML
XMLdocumentsthatconformtothesyntaxrulesabovearesaidtobe"WellFormed"XMLdocuments.
http://www.w3schools.com/xml/xml_syntax.asp
4/4
12/13/2016
XMLTree
XMLTree
w3schools.com/xml/xml_tree.asp
XMLdocumentsformatreestructurethatstartsat"theroot"andbranchesto"theleaves".
XMLTreeStructure
AnExampleXMLDocument
TheimageaboverepresentsbooksinthisXML:
<?xmlversion="1.0"encoding="UTF8"?>
<bookstore>
<bookcategory="cooking">
<titlelang="en">EverydayItalian</title>
<author>GiadaDeLaurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<bookcategory="children">
<titlelang="en">HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<bookcategory="web">
<titlelang="en">LearningXML</title>
<author>ErikT.Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
http://www.w3schools.com/xml/xml_tree.asp
1/2
12/13/2016
XMLTree
XMLTreeStructure
XMLdocumentsareformedaselementtrees.
AnXMLtreestartsatarootelementandbranchesfromtheroottochildelements.
Allelementscanhavesubelements(childelements):
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
Thetermsparent,child,andsiblingareusedtodescribetherelationshipsbetweenelements.
Parenthavechildren.Childrenhaveparents.Siblingsarechildrenonthesamelevel(brothersandsisters).
Allelementscanhavetextcontent(HarryPotter)andattributes(category="cooking").
SelfDescribingSyntax
XMLusesamuchselfdescribingsyntax.
AprologdefinestheXMLversionandthecharacterencoding:
<?xmlversion="1.0"encoding="UTF8"?>
Thenextlineistherootelementofthedocument:
<bookstore>
Thenextlinestartsa<book>element:
<bookcategory="cooking">
The<book>elementshave4childelements:<title>,<author>,<year>,<price>.
<titlelang="en">EverydayItalian</title>
<author>GiadaDeLaurentiis</author>
<year>2005</year>
<price>30.00</price>
Thenextlineendsthebookelement:
</book>
Youcanassume,fromthisexample,thattheXMLdocumentcontainsinformationaboutbooksinabookstore.
http://www.w3schools.com/xml/xml_tree.asp
2/2
12/13/2016
XMLTutorial
XMLTutorial
w3schools.com/xml/
XMLstandsforeXtensibleMarkupLanguage.
XMLwasdesignedtostoreandtransportdata.
XMLwasdesignedtobebothhumanandmachinereadable.
XMLExample1
<?xmlversion="1.0"encoding="UTF8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don'tforgetmethisweekend!</body>
</note>
XMLExample2
<?xmlversion="1.0"encoding="UTF8"?>
<breakfast_menu>
<food>
<name>BelgianWaffles</name>
<price>$5.95</price>
<description>
TwoofourfamousBelgianWaffleswithplentyofrealmaplesyrup
</description>
<calories>650</calories>
</food>
<food>
<name>StrawberryBelgianWaffles</name>
<price>$7.95</price>
<description>
LightBelgianwafflescoveredwithstrawberriesandwhippedcream
</description>
<calories>900</calories>
</food>
<food>
<name>BerryBerryBelgianWaffles</name>
<price>$8.95</price>
<description>
Belgianwafflescoveredwithassortedfreshberriesandwhippedcream
</description>
<calories>900</calories>
</food>
<food>
<name>FrenchToast</name>
<price>$4.50</price>
<description>
Thickslicesmadefromourhomemadesourdoughbread
http://www.w3schools.com/xml/
1/2
12/13/2016
XMLTutorial
</description>
<calories>600</calories>
</food>
<food>
<name>HomestyleBreakfast</name>
<price>$6.95</price>
<description>
Twoeggs,baconorsausage,toast,andoureverpopularhashbrowns
</description>
<calories>950</calories>
</food>
</breakfast_menu>
WhyStudyXML?
XMLplaysanimportantroleinmanydifferentITsystems.
XMLisoftenusedfordistributingdataovertheInternet.
Itisimportant(foralltypesofsoftwaredevelopers!)tohaveagoodunderstandingofXML.
WhatYouWillLearn
ThistutorialwillgiveyouasolidunderstandingofXML:
WhatisXML?
HowdoesXMLwork?
HowcanIuseXML?
WhatcanIuseXMLfor?
http://www.w3schools.com/xml/
2/2
12/13/2016
XMLUsage
HowCanXMLbeUsed?
w3schools.com/xml/xml_usedfor.asp
XMLisusedinmanyaspectsofwebdevelopment.
XMLisoftenusedtoseparatedatafrompresentation.
XMLSeparatesDatafromPresentation
XMLdoesnotcarryanyinformationabouthowtobedisplayed.
ThesameXMLdatacanbeusedinmanydifferentpresentationscenarios.
Becauseofthis,withXML,thereisafullseparationbetweendataandpresentation.
XMLisOftenaComplementtoHTML
InmanyHTMLapplications,XMLisusedtostoreortransportdata,whileHTMLisusedtoformatanddisplay
thesamedata.
XMLSeparatesDatafromHTML
WhendisplayingdatainHTML,youshouldnothavetoedittheHTMLfilewhenthedatachanges.
WithXML,thedatacanbestoredinseparateXMLfiles.
WithafewlinesofJavaScriptcode,youcanreadanXMLfileandupdatethedatacontentofanyHTMLpage.
Books.xml
<?xmlversion="1.0"encoding="UTF8"?>
<bookstore>
<bookcategory="cooking">
<titlelang="en">EverydayItalian</title>
<author>GiadaDeLaurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<bookcategory="children">
<titlelang="en">HarryPotter</title>
<author>JK.Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<bookcategory="web">
<titlelang="en">XQueryKickStart</title>
<author>JamesMcGovern</author>
<author>PerBothner</author>
http://www.w3schools.com/xml/xml_usedfor.asp
1/3
12/13/2016
XMLUsage
<author>KurtCagle</author>
<author>JamesLinn</author>
<author>VaidyanathanNagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<bookcategory="web"cover="paperback">
<titlelang="en">LearningXML</title>
<author>ErikT.Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
YouwilllearnalotmoreaboutusingXMLandJavaScriptintheDOMsectionofthistutorial.
TransactionData
ThousandsofXMLformatsexists,inmanydifferentindustries,todescribedaytodaydatatransactions:
StocksandShares
Financialtransactions
Medicaldata
Mathematicaldata
Scientificmeasurements
Newsinformation
Weatherservices
Example:XMLNews
XMLNewsisaspecificationforexchangingnewsandotherinformation.
Usingastandardmakesiteasierforbothnewsproducersandnewsconsumerstoproduce,receive,and
archiveanykindofnewsinformationacrossdifferenthardware,software,andprogramminglanguages.
AnexampleXMLNewsdocument:
<?xmlversion="1.0"encoding="UTF8"?>
<nitf>
<head>
<title>ColombiaEarthquake</title>
</head>
<body>
<headline>
<hl1>143DeadinColombiaEarthquake</hl1>
</headline>
<byline>
<bytag>ByJaredKotler,AssociatedPressWriter</bytag>
</byline>
<dateline>
<location>Bogota,Colombia</location>
http://www.w3schools.com/xml/xml_usedfor.asp
2/3
12/13/2016
XMLUsage
<date>MondayJanuary2519997:28ET</date>
</dateline>
</body>
</nitf>
Example:XMLWeatherService
AnXMLnationalweatherservicefromNOAA(NationalOceanicandAtmosphericAdministration):
<?xmlversion="1.0"encoding="UTF8"?>
<current_observation>
<credit>NOAA'sNationalWeatherService</credit>
<credit_URL>http://weather.gov/</credit_URL>
<image>
<url>http://weather.gov/images/xml_logo.gif</url>
<title>NOAA'sNationalWeatherService</title>
<link>http://weather.gov</link>
</image>
<location>NewYork/JohnF.KennedyIntlAirport,NY</location>
<station_id>KJFK</station_id>
<latitude>40.66</latitude>
<longitude>73.78</longitude>
<observation_time_rfc822>Mon,11Feb200806:51:000500EST
</observation_time_rfc822>
<weather>AFewClouds</weather>
<temp_f>11</temp_f>
<temp_c>12</temp_c>
<relative_humidity>36</relative_humidity>
<wind_dir>West</wind_dir>
<wind_degrees>280</wind_degrees>
<wind_mph>18.4</wind_mph>
<wind_gust_mph>29</wind_gust_mph>
<pressure_mb>1023.6</pressure_mb>
<pressure_in>30.23</pressure_in>
<dewpoint_f>11</dewpoint_f>
<dewpoint_c>24</dewpoint_c>
<windchill_f>7</windchill_f>
<windchill_c>22</windchill_c>
<visibility_mi>10.00</visibility_mi>
<icon_url_base>http://weather.gov/weather/images/fcicons/</icon_url_base>
<icon_url_name>nfew.jpg</icon_url_name>
<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
</current_observation>
http://www.w3schools.com/xml/xml_usedfor.asp
3/3
12/13/2016
XSL(T)Languages
XSL(T)Languages
w3schools.com/xml/xsl_languages.asp
XSLTisalanguagefortransformingXMLdocuments.
XPathisalanguagefornavigatinginXMLdocuments.
XQueryisalanguageforqueryingXMLdocuments.
ItStartedwithXSL
XSLstandsforEXtensibleStylesheetLanguage.
TheWorldWideWebConsortium(W3C)startedtodevelopXSLbecausetherewasaneedforanXMLbased
StylesheetLanguage.
CSS=StyleSheetsforHTML
HTMLusespredefinedtags.Themeaningof,andhowtodisplayeachtagiswellunderstood.
CSSisusedtoaddstylestoHTMLelements.
XSL=StyleSheetsforXML
XMLdoesnotusepredefinedtags,andthereforethemeaningofeachtagisnotwellunderstood.
A<table>elementcouldindicateanHTMLtable,apieceoffurniture,orsomethingelseandbrowsersdonot
knowhowtodisplayit!
So,XSLdescribeshowtheXMLelementsshouldbedisplayed.
XSLMoreThanaStyleSheetLanguage
XSLconsistsoffourparts:
XSLTalanguagefortransformingXMLdocuments
XPathalanguagefornavigatinginXMLdocuments
XSLFOalanguageforformattingXMLdocuments(discontinuedin2013)
XQueryalanguageforqueryingXMLdocuments
WiththeCSS3PagedMediaModule,W3Chasdeliveredanewstandardfordocumentformatting.So,since
2013,CSS3isproposedasanXSLFOreplacement.
WhatisXSLT?
XSLTstandsforXSLTransformations
XSLTisthemostimportantpartofXSL
XSLTtransformsanXMLdocumentintoanotherXMLdocument
http://www.w3schools.com/xml/xsl_languages.asp
1/2
12/13/2016
XSL(T)Languages
XSLTusesXPathtonavigateinXMLdocuments
XSLTisaW3CRecommendation
XSLT=XSLTransformations
XSLTisthemostimportantpartofXSL.
XSLTisusedtotransformanXMLdocumentintoanotherXMLdocument,oranothertypeofdocumentthatis
recognizedbyabrowser,likeHTMLandXHTML.NormallyXSLTdoesthisbytransformingeachXMLelement
intoan(X)HTMLelement.
WithXSLTyoucanadd/removeelementsandattributestoorfromtheoutputfile.Youcanalsorearrangeand
sortelements,performtestsandmakedecisionsaboutwhichelementstohideanddisplay,andalotmore.
AcommonwaytodescribethetransformationprocessistosaythatXSLTtransformsanXMLsourcetree
intoanXMLresulttree.
XSLTUsesXPath
XSLTusesXPathtofindinformationinanXMLdocument.XPathisusedtonavigatethroughelementsand
attributesinXMLdocuments.
IfyouwanttostudyXPathfirst,pleasereadourXPathTutorial.
HowDoesitWork?
Inthetransformationprocess,XSLTusesXPathtodefinepartsofthesourcedocumentthatshouldmatchone
ormorepredefinedtemplates.Whenamatchisfound,XSLTwilltransformthematchingpartofthesource
documentintotheresultdocument.
http://www.w3schools.com/xml/xsl_languages.asp
2/2
12/13/2016
XSLTIntroduction
XSLTIntroduction
w3schools.com/xml/xsl_intro.asp
XSL(EXtensibleStylesheetLanguage)isastylinglanguageforXML.
XSLTstandsforXSLTransformations.
ThistutorialwillteachyouhowtouseXSLTtotransformXMLdocumentsintootherformats(liketransforming
XMLintoHTML).
OnlineXSLTEditor
Withouronlineeditor,youcaneditXMLandXSLTcode,andclickonabuttontoviewtheresult.
XSLTExample
<?xmlversion="1.0"?>
<xsl:stylesheetversion="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:templatematch="/">
<html>
<body>
<h2>MyCDCollection</h2>
<tableborder="1">
<trbgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:foreachselect="catalog/cd">
<tr>
<td><xsl:valueofselect="title"/></td>
<td><xsl:valueofselect="artist"/></td>
</tr>
</xsl:foreach>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
http://www.w3schools.com/xml/xsl_intro.asp
1/1