Tải bản đầy đủ

Addison wesley secure XML the new syntax for signatures and encryption jul 2002 ISBN 0201756056

6.2DataModel
TheXPathdatamodelisrelativelysimple.AnyXMLdocument
orobjectisasetofnodesofoneofseventypes(listedbelow).
Thesenodesareorganizedintoahierarchicaltree.Inaddition
tothistreestructure,alinearorderingofthenodesis
maintained;thisorderingiscalled"documentorder."
Thedocumentorderofnodesmatchestheorderinwhichthe
firstcharacterofthatnodeappearsinthedocumentcharacter
stringform.Thusanelementnodeprecedesallofitschildren,
becausetheelementstarttag'sopeningleftanglebracket
occursbeforeallelementcontent,attributes,ornamespace
declarations.Byconvention,therootnode,whichhasno
characterrepresentation,comesfirstindocumentorder:
Rootnode
Elementnodes
Attributenodes
Namespacenodes
Textnodes
Processinginstructionnodes
Commentnodes
NotethatnoprovisionismadeforDTDsortheXMLdeclaration.

Ineffect,XPathtakesthepointofviewthatDTDsandtheXML
declarationarepartoftheexternalformofXML.Afterreading
XMLintoanapplication,theDTDanddeclarationhavealready


beentakenintoaccountandarenolongeruseful.Similarly,the
parsingofcharactersintoanXPathnode-setremovesexternal
artifactssuchasCDATAsectionsandcharacterreferences.
Example6-1andFigure6-2provideanexampleofsomeXML
andtheresultingXPathdatamodel.
Figure6-2.Xpathdatamodel

Example6-1ExternalXML


qwertyuiop


ThefollowingsectionsdescribethesevennodetypesinXPath,


includingthestringvalueandextendednameforeachnode
type.InXPath,everynodehasa"stringvalue"andsomehave
"extendednames";bothofthesevaluesareaccessiblethrough
XPathfunctions,asdescribedinSection6.5.

6.2.1RootNodes
EveryXPathnode-sethasoneandonlyonerootnodeforits
tree.Thetop-levelelementofanXMLdocument,oftencalled
the"rootelement,"isachildoftheXPathrootnodeinthe
XPathnode-setforthatdocument.Itisnecessarytoprovide
therootnodebecausecommentsandprocessinginstructions
canappearbothbeforeandaftertherootelement.Theroot
nodeistheparentofsuchoutside-of-documentnodes.Many
usesofXPathareintendedtoalsoapplytogeneralexternal
parsedentitiesandsoallowmultipleelementchildrenofthe
rootnode.
Therootnodehasnoparent.EveryothernodeinanXPath
node-sethasexactlyoneparent.


Thestringvalueoftherootnodeistheconcatenationofthe
stringvalueofalltextnodedescendantsoftherootnodes
organizedindocumentorder.Rootnodesdonothaveextended
names.

6.2.2ElementNodes
AnelementnodeexistsforeachelementintheoriginalXML
object.TheXPathstringvalueofanelementisthe
concatenationofthestringvaluesofallofitstextnode
descendants.Forexample,thetextvalueof

(onethreefoursix?>sevennine)xyz


is

(onethreefoursevennine)xyz
Theextendednameofanelementnodeisitslocalnameand
theURIofitsnamespace,ifany.Itmayconsistofthe
namespaceboundtoitsnamespaceprefixifoneispresentor
thedefaultnamespaceifnoprefixispresent.TheURIofthe
extendednameisnullonlyifnonamespaceprefixexistsand
thedefaultnamespaceisnullornotdeclaredinscope.

6.2.3AttributeNodes
Everyelementnodehasanassociatedandpossiblyemptyset
ofattributenodes.(Namespacedeclarationsarenotattributes,
althoughtheymaylooklikethem.)AlthoughXPathconsiders
theelementtobetheparentofitsattributenodes,itdoesnot
considertheattributenodestobechildrenordescendantsof
theirelement.Asaconsequence,toaccesstheattributenodes,
anapplicationmustusedifferentXPathoperationsthanthe
applicationusestoaccesschildren.Thistreatmentofattributes
inXPathdiffersfromthatfoundintheDocumentObjectModel
[DOM]:DOMdoesnottreatelementsastheparentsoftheir
attributes.
BecausetheXPathmodelisinvokedafterXMLhasbeenparsed
byanapplicationoninput,theXPathnode-setincludesthe
defaultattributes.Attributesinthexmlnamespace,which
affectalldescendantsofanelementuntiltheyareoverridden,
suchasxml:lang,neverthelessappearonlyassingleattribute
nodesfortheelementsinwhosestarttagstheyoccur.
Thestringvalueofanattributenodeisthenormalizedattribute
value.See[XML].
TheextendednameofanattributeisitslocalnameandtheURI
ofitsnamespaceifithasanamespaceprefix.TheURIpartof


theextendednameisnullifnonamespaceprefixispresent.

6.2.4NamespaceNodes
AsshowninExample6-1andFigure6-2,namespace
declarationsdonotsimplycreatenamespacenodesattachedto
theelementinwhosestarttagthenamespacedeclaration
occurs.Rather,XPathcreatesnamespacenodesbelowall
descendantelementsofthatelement,exceptatandbelow
elementnodeswhereanewnamespacedeclarationwiththe
sameprefixoverridestheancestraldeclaration.
PerhapsXPathdecidedtoreplicatethenamespacedeclarationnodes
overdescendantelementstomakeiteasiertoaccessthesetof
namespacedeclarationsinscope.Inreality,thischoicedestroys
information.ConsiderExample6-2.Afterparsingandconversiontoan
XPathnode-set,itisnolongerpossibletotellthatthenamespace
declarationofprefix"x"appearedonelement"B."Becauseofthe
namespacedeclarationatelement"A,"XPathwouldhavecreateda
namespacenodeatalldescendantsof"A"and"B,"evenifthatsame
namespacedeclarationhadnotoccurredat"B."Similarly,after
conversiontoanXPathnode-set,youcan'ttellwhetherthisdeclaration
occurredonelements"C"or"D"intheinput.Thisproblemmakes
canonicalizationmoredifficult,asexplainedinChapter9.

ThestringvalueofanamespacenodeisthenamespaceURI
thatisboundtotheprefix.Thusthestringvalueofthe
namespacenodescreatedinExample6-2is

http://foo.example/bar
Asyoumightguess,theextendednameforanamespacenode
hastheprefixandthelocalnameandtheURIasthe
namespace.Ifthedeclarationinvolvesthedefaultprefix,the
localnameisnull.


Example6-2XPathandnamespaces






6.2.5TextNodes
Charactercontentappearsastextnodes.Textnodesalways
haveatleastonecharacterinthem,andatextnodeinthefull
XPathnode-setneverhasanadjacenttextnode.Contiguous
textintheoriginalinput,howeverlong,appearsasasingletext
node.AnXPathselection,however,canselecttwoormoretext
nodeswithoutselectinterveningnodesofothertypes.
Processingthesenodescan,therefore,resultinprocessingof
twoormoretextnodesinarow.
Thecharacterdatainatextnodeistheinternalapplication
version.ThusCDATAsectionshavealreadybeenprocessed,the
characterreferredtoreplacescharacterreferences,andsoon.
Forexample,theexternalrepresentation

""<]]>&"
appearsasatextnodewithcontent

">"<&"
Thestringvalueofatextnodeisitscharacterdata.Atextnode
hasnoextendedname.

6.2.6ProcessingInstructionNodes


Theextendednameofaprocessinginstructionisthetarget
nameoftheprocessinginstructionwithanullURI.Thestring
valueofaprocessinginstructionisthepartoftheinstruction
thatoccursafterthetargetandafteranywhitespace
separatingitfromthetarget.Thestringvaluedoesnotinclude
theterminating"?>".Thus


hasanullstringvalue,whereas


hasthestringvalue"Bokm42yZgv".
NotethatanyprocessinginstructionsintheDTDandtheXML
declarationdonotappearasnodesofanysortinthe
correspondingXPathnode-set.Otherthanthat,aprocessing
instructionnodecorrespondstoeachprocessinginstructionin
theexternalXML.(AlthoughtheXMLdeclarationlookslikea
processinginstruction,itisdefinednottobeone.)

6.2.7CommentNodes
Acommentnodedoesnothaveanextendedname.Thestring
valueofacommentcompriseseverythingbetweentheopening
"".Forexample,thestringvalueof


isnull,whereasthatof


is"FourscoreandSeven."


7.3XPointer
XPointeristhesyntaxyouuseforthemostgeneraladdressing
ofpartsofanXMLobject[XPointer].WhenanHTTPURI
referencesXML,anyfragmentspecifiertoselectaportionofthe
XMLiswritteninXPointersyntax.XPointercanalsobecalled
explicitlytoextractasubsetofdata(seeChapter19).Notethat
XPointerdoesnotincludeanywaytopointintotheDTDorXML
declarationforadocument.
XPointerextendsXPathsothatyoucanuseitinthefollowing
ways:
AsafragmentidentifierinaURIreference
Tolocateinformationbystringmatching
ToaddresspointsandrangeswithinXML

InXMLSecurityURIs,youshouldrarelyencounteranythingotherthan
verysimpleXPointers.TheimplementationmightdelegateURIretrieval
andfragmentspecifierprocessingtoseparatecodewithsomewhat
unpredictableresults.Forthisreason,theXMLSecuritystandards
discourageuseofXPointerfragmentspecifiersinfavorofusingthe
explicit"Transforms"mechanismprovided.(Whileyoucaninvokethe
fullpowerofXPointerinsuchtransforms,fullsupportforitisoptional.
EvenfullsupportofXPath,onwhichXPointerbuilds,ismerely
recommended,notmandatory.)

XPointerEncoding
WhenanXPointercontainsspecialcharactersthathave


significancetoXPointerbutthatshouldbetreatedasdata,a
circumflex("^")prefixesthespecialcharacters.Oneexample
wouldbeanunbalancedparenthesis—either"("or")"—
appearinginaliteralstring.Duetothisuse,circumflexitself
mustbeconsideredaspecialcharacterandoccurrencesofa
literalcircumflexdoubled("^^").Forexample,

xpointer(string-range(/.,"f)^"))
wouldbeencodedasfollows:

xpointer(string-range(/.,"f^)^^"))
TheprecedingruleappliesonlytogeneralXPointerencoding.
AnXPointermustalsobeURIencoded(seeSection7.1.4)ifit
isusedinaURIandXMLencodedifitappearsinXML.So,for
example,

xpointer(string-range(//example,"André:-)"))
wouldalwaysbeXPointerencodedfortheunbalanced
parenthesisinthe"smiley"asfollows:

xpointer(string-range(//example,"André:-^)"))
IfitappearedassuchinanXMLattributevaluedelimitedby
doublequotesandencodedinUS-ASCII,youwouldescapethe
doublequotesandtheaccented"é":

xpointer(string-range(//example,"André:-^)&q
IfitappearedgenerallyasaURIreferencefragmentspecifier,
youwouldencodethespace,doublequotes,circumflex,and
accented"é":

xpointer(string-range(//example,%22Andr%C3%A9%20:-%5E)%


7.3.1FormsofXPointer
XPointerhasthreepossibleforms:
FullXPointers
Barenames
Childsequences

FullXPointers
AfullXPointercanbecomplicated,butyouwillrarelyencounter
thefullform.Itconsistsofasequenceofoneormoreparts
thatcanoptionallybeseparatedbywhitespace.Eachparthas
thefollowingformat:

scheme(string-with-balanced-parentheses)
The"xpointer"and"xmlns"schemesaredefinedbelow.The
"string-with-balanced-parentheses"meansanystringwhereall
parentheses—both"("and")"—areproperlynested,exceptfor
thoseescapedwiththecircumflex("^"),asdescribedearlier.
FullXPointerpartsendwithacloseparenthesisthatmatches
theopenparenthesisaftertheschemename.
Ifmultiplepartsarepresent,theyareevaluatedfromleftto
rightuntilonesucceeds.Ifallpartsfail,thenthefullXPointer
fails.Asyetundefinedschemesarepermittedforfuture
expansion.Encounteringaschemeyoudonotunderstandis
equivalenttoafailureofthatpart.(Thisscheme-basedsystem
allowsotherdatatypesthangeneralXMLtodefinetheirown
schemes.)
Youusethe"xmlns"schemetosetupthenamespacecontext


forXPointerexpressionevaluationsoccurringfarthertothe
right.Theparenthesizedstringimmediatelyafterthisscheme
mustconsistofanamespaceprefixfollowedbyanamespace
URI.DonotusequotationmarksaroundtheURI.Forexample:

xmlns(foo=http://bar.example/x)
The"xmlns"schemeaddsitsnamespacedeclarationtothe
namespacecontextandthen"fails"sothatevaluationproceeds
tothenextpartofthefullXPointertoitsright.Iftwo"xmlns"
partstrytobindthesameprefix,theoneevaluatedlater(the
onefarthertotheright)overridesthefirst.Those"xmlns"parts
thatattempttobindthe"xml"prefixareignored.Instead,the
prefixisalwaysboundto
"http://www.w3.org/XML/1998/namespace";thisbindingis
alwayspartofthenamespacecontextforevaluatingXPointer
expressions.
The"xpointer"schemedoestheobviousthing—namely,it
interpretstheparenthesizedstringimmediatelyafteritasan
XPointerexpression.Ifitisevaluatedwithouterrorandyieldsa
nonemptylocation-set,thenthatresultisthevalueoftheentire
fullXPointer.
YoucanusetheabilitytoprovideasequenceofXPointerparts
forvariouspurposes.ThefollowingexampleshowsgeneralfailoverfromoneXPointerexpressiontoanother.Itfindsall"foo"
elementsthatdon'thaveafoodescendantor,ifnosuchfoo
elementsarepresent,all"bar"elementsthatdonothaveany
children.

xpointer(//*foo[not(.//foo)])xpointer(//*bar[not(./*)]
BareNames
IncomparisonwithafullXPointer,itisdifficulttogetmuch


simplerthanabarename.Abarenameisprettymuchlikeit
sounds—justatoken.Itreferstotheelementwiththattoken
asanID.Inotherwords,thebarenamefragmentspecifier

#foo
isthesameasthefullXPointerfragmentspecifier

#xpointer(id("foo"))
ChildSequences
Achildsequenceconsistsofaseriesofoneormoredecimal
numbersprecededbyaslash("/")andseparatedbyslashes.
Nowhitespaceispermitted.Thesequencemaybeoptionally
prefixedwithabarename.Twoexamplefragmentspecifiersare
shownhere:

#/2/7/18/2/8
#pi/3/14/
Suchsequencescanonlylocateelements.Theydosobyusing
eachnumbertoindexintothechildrenoftheelementfoundby
thepreviousstep.Thestartingpointistherootelement,ifthe
childsequencestartswithaslash,ortheelementthatthe
nameasanIDspecifies(ifitstartswithaname).The
precedingexamplesarethereforeequivalenttothefollowing:

#xpointer(/*[2]/*[7]/*[18]/*[2]/*[8])
#xpointer(id("pi")/*[3]/*[14])
7.3.2TheXPathExtensions
XPathdealsonlywithnodes.XPointerextendsXPath,however,
sothatitcanhandlemoregenerallocations.Thelocations


permittedincludeapointerintothemiddleoftextaswellas
moregeneralranges,suchasmightresultfromauserclicking
anddraggingonascreendisplayofXMLtoincludepartsoftwo
elementswithdifferentparents.Insummary,theextensionsto
XPathhavethefollowingeffects:
Theconceptsofanodeandanode-setareextendedto
includealocationandalocation-set.Ineffect,thetwo
locationtypesof"point"and"range"havethesamestatus
asnodetypesandappropriateextensionsaremadetonode
testsandthedefinitionsofaxes.Whileevaluatingan
expression,thecontextlocationisextendedsothatitcan
consistofapointorrange.Also,youcanusetheXPath"
[number]"predicatetoselectvaluesfromasetofpoints
andranges.
Theextensionsprovideextendedrulesforestablishingthe
XPathevaluationcontext.
Numerousadditionalfunctionsareadded,aslistedin
Section7.3.3.Aspecial-caseextensionappliestothe
expressionsyntaxforthe"range-to,"asexplainedwiththat
function'sdefinition.
Therootnodemayhavemultiplechildelements.This
principleallowsXPointersintogeneralexternalparsed
entities,whichmightconsistofmultipletop-levelelements.

LocationExtension:Point
XPointeraddsthe"point"typetoXPath,definedasfollows:
Apointisdefinedasanindexandacontainernode.It
alwayspointsbeforethefirstiteminthecontainer,between


twoitemsinthecontainer,orafterthelastiteminthe
container.
Ifthecontainerisanelementorrootnode,theitemsareits
children.
IfthereareNchildren,anindexofzeropointsjustbefore
thefirstchild;anindexofNpointsjustafterthelastchild;
andanindexofX,where0andX+1.Suchapointintochildreniscalleda"nodepoint."
Ifacontainerdoesnothavechildrenbutdoeshaveastring
value,thentheindexpointsbetweencharactersinthat
stringvalue.IfthestringvaluelengthisN,anindexofzero
pointsjustbeforethefirstcharacter;anindexofNpoints
justafterthelastcharacter;andanindexofX,where0intotextiscalleda"character-point."
Youneedtobecarefulaboutthinkingofa"point"asjusta
locationintheexternalrepresentationofXML.Forexample,
consider"xyz".Itisanelementnodewithachildtext
node.Thepointusingthiselementascontainerandindex1is
thepointjustafterthetextnode.Thepointusingthetextnode
asacontainerandindex3isthepointjustafterthelast
characterinthetext.Althoughthetwoaredifferentpoints,a
poorlydesigneduserinterfacemightdisplaythem
indistinguishablyonacomputerscreen.
Apointlocationdoesnothaveanexpandedname.Itdoeshave
anullstringvalue.
TheXPathsetofnodetestsisextendedtoinclude"point()"so
thatpointscanbeselectedfromalocation-set.Theaxesofa
pointarelocation-setsdefinedasfollows:


The"self::"axiscontainsthepointitself.
The"parent::"axiscontainsthepoint'scontainernode.
The"ancestor::"axiscontainsthepointcontainernodeand
itsancestors.
The"child::","descendant::","preceding-sibling::",
"following-sibling::","attribute::",and"namespace::"axes
areempty.
AlthoughtheyarenotdefinedintheXPointerdocument,
onewouldpresumethatthe"descendant-or-self::"axis
containsjustthepointitself,thatthe"ancestor-or-self::"
axisistheunionofthe"self::"and"ancestor::"axes,and
thatthe"following::"and"preceding::"axesareempty.

LocationExtension:Range
XPointeraddstoXPaththe"range"type.Arangeissimply
definedastwopoints:thestartpointandtheendpointofthe
range.Thestartpointmustnotfollowtheendpoint,andboth
mustappearinthesameXMLdocument.Therangerepresents
theXMLcontentandstructurebetweenitspoints.
Ifthecontainernodeofonepointofarangeisanelement,
text,orroot,thenthecontainernodeoftheotherpointmust
alsobeoneofthesethreetypes.Ifthecontainernodeofone
suchpointisanyothertype,thenboththestartandendpoint
mustresidewithinthesamenode.
Forexample,youcanhavearangethatappearswithinthe
stringvalueofaprocessinginstruction,wherebothpointshave
theprocessinginstructionastheircontainernode.Alternatively,
forarangefromaprocessinginstructionto(andincluding)an


immediatelyfollowingelement,thepointsoftherangemight
haveastheircontainernodestheparentsoftheprocessing
instructionandelement.Youcouldnot,however,havearange
frominsidethetextcontentofaprocessinginstructiontoinside
thetextcontentofafollowingelement.
Arangewiththesamestartandendpointiscalledacollapsed
range.Arangelocationdoesnothaveanexpandedname.
Thestringvalueofarangedependsonthenatureofitspoints.
Ifbotharecharacter-pointsinthesamecontainernode,the
stringvalueis—justasyouwouldexpect—thecharacters
betweenthestartandendpoints.Otherwise,thestringvalue
consistsofthecharactersintextnodesforwhichthecharacter
isfoundafterthestartpointandbeforetheendpoint.For
example,in

1#23fooxy#z
thestringvalueofarangefromjustafterthefirstoctothorpe
("#")tojustbeforethesecondwouldsimplybe

23fooxy
Inthesameexample,thestringvalueoftherangefromjust
beforeelement"a"tojustafterelement"a"is

1#23fooxy#z
TheXPathsetofnodetestsisextendedtoinclude"range()"so
thatrangescanbeselectedfromalocation-set.
Theaxesofarangearethesameastheaxesofthestartpoint
ofthatrange.

CoveringRanges


XPointerdefinestheconceptofacoveringrange.Acovering
rangethatencompassesanytypeoflocationcanbefoundas
follows:
Thecoveringrangeofarangeisthatrange.
Thecoveringrangeforapointisthecollapsedrange
startingandendingwiththatpoint.
Fortherootnode,thestartandendpointsofthecovering
rangehavetherootnodeastheircontainer.Theindexof
thestartpointiszero,andtheindexoftheendpointisthe
numberofchildrenoftheroot.
Foranattributeornamespacenode,thestartandend
pointsofthecoveringrangehavetheattributeor
namespacenodeastheircontainer.Theindexofthestart
pointiszero,andtheindexoftheendpointisthelengthof
thestringvalueoftheattributeornamespacenode.
Forallotherkindsofnodes,thestartandendpointsofthe
coveringrangehavetheparentofthatnodeastheir
container.Theindexofthestartpointisthenumberof
precedingsiblingnodes,andtheindexoftheendpointis
onegreaterthanthestartpoint.Thusthecoveringrangeof
anelementisthepairofnode-pointstojustbeforeandjust
afterthatelement.

DocumentOrder
XPointerextendstheXPathconceptof"documentorder"to
includepointsandranges.
First,a"precedingnode"isdefinedforallpointsasfollows:


Foranode-pointwithanonzeroindexX,thepreceding
nodeistheXthchildofthecontainernode.
Foranode-pointwithazeroindex,theprecedingnodeis
thecontainernode,unlessithasattributesornamespaces.
Inthatcase,itisthelastattributeornamespace
declaration.
Foracharacter-point,theprecedingnodeisitscontainer
node.
Usingthesedefinitions,youcanfinddocumentorderingsthat
XPathdoesnotspecify:
Anodeislocatedbeforeapointifitisbeforeorthesame
astheprecedingnodeofthatpoint.Otherwise,itisfound
afterthepoint.
Thedocumentorderofanodeandarangematchesthe
documentorderofthatnodeandthestartpointofthe
range.
Thedocumentorderoftwopointsmatchesthedocument
orderoftheirprecedingnodes.Iftheyareidentical,the
pointwiththesmallerindexcomesfirst.(Ifboththe
precedingnodeandtheindicesofthepointsareequal,they
arethesame.)
Thedocumentorderofapointandarangematchesthe
documentorderofthatpointandthestartpointofthe
range.
Thedocumentorderoftworangesmatchesthedocument
orderoftheirstartpoints,unlesstheyhavethesamestart
point.Inthatcase,itisthedocumentorderoftheirend


points.

InitializationofEvaluationContext
TheevaluationofXPointerexpressionsoccursinthesameway
astheevaluationofXPathexpressions,albeitwithafew
changes:
Thecontextlocationisinitializedtoarootnode.ForaURI
referencefragmentspecifierXPointerexpression,itisthe
rootnodeofthedocumentthattherestoftheURI
specifies.ForotherXPointeruse—forexample,theXPointer
transformdescribedinChapter19—theinitialrootnodeis
specifiedbytheapplication.
Thecontextpositionandsizeareinitializedto1.
Anemptysetofvariablebindingsisused.
ThelibraryoffunctionsmatchesthatdefinedinChapter6
forXPathandSection7.3.3.
Asetofnamespacedeclarationsisprovided,asdescribed
earlierinthischapter.

7.3.3XPointerFunctions
ThefollowingfunctionshavebeenaddedtothecoreXPath
functionlibraryfortheevaluationofXPointerexpressions.In
thissection,thefunctionnameappearsinboldface,preceded
bythedatatypeoftheresultinitalics.Parametersare
representedbytheirdatatypeinitalics.Parametersare
followedbyaquestionmarkwhentheyareoptional.


Alocation-setisasupersetofanode-set.Nodesarealsolocations.
Thus,whereveraparameterisshownasbeingoftypelocation-set,you
maysupplyanode-setwithoutadatatypemismatchoccurring.

location-setend-point(location-set)
Theresultisapointforeachlocationintheinputasspecified
bythefollowingrules:
Foraninputpoint,theoutputelementisthesamepoint.
Foraninputrange,theoutputelementistheendpointof
therange.
Forarootorelementnodeinput,theoutputisthepoint
justafterthelastchildoftheinput.Thatis,theoutput
pointhasacontainernodeoftheinputnodeandanindex
ofthenumberofchildrenoftheinput.
Foratext,comment,orprocessinginstructionnode,the
outputisthepointjustaftertheendofthetextcontent.
Thatis,theoutputpointhasacontaineroftheinputnode
andanindexofthelengthofthestringvalueoftheinput.
Foranattributeornamespacenode,theXPointerinwhich
thisfunctionappearsfails.
location-sethere()
ThisfunctionfailsiftheXPointerwhereitappearsisnotinXML.
IfitisinXML,thenthefunctionreturnsalocation-setwitha
singlemember.IftheXPointerexpressionbeingevaluated


occurredinatextnode,thenthefunctionreturnstheparent
element.Otherwise,itreturnsthenodecontainingtheXPointer,
presumablyanattributeorprocessinginstructionnode.(When
anXPointeroccursaselementcontent,itisn'tactuallyinthat
elementbutratherappearsinatextchildofthatelement.)
location-setorigin()
Thisfunctionprovidesaddressingrelativetotheoriginofthe
linktraversedtoreachthedocumentcontainingtheXPointer.It
returnsalocation-setwithasinglemember—theelementfrom
whichthetraversalwasinitiated.Anerroroccursifyouinvoke
thisfunctionwherenosuchtraversalhasoccurredorthe
documentfromwhichtraversaloccurredisnotXML.Youcannot
usethisfunctioninaURIreferencefragmentidentifierwherea
URIisalsoprovided,unlessthatURIidentifiesthesame
resourcefromwhichthetraversalwasinitiated.See[Xlink]for
moreinformationontraversal.
location-setrange(location-set)
Thisfunctionreturnstherangescoveringallitemsintheinput.
Acoveringrangeisaddedtotheoutputforeachmemberofthe
input.
location-setrange-inside(location-set)
Thisfunctionreturnstherangescoveringthecontentsofall
itemsintheinput.Foreveryinputitemthatisarangeorpoint,
thatrange(orthecollapsedrangeofthepoint)isadded.Forall
othertypesofinputitem,arangeisaddedwiththatitemasthe
containernodeandastartpointindexofzero.Theendpoint
indexisthenumberofchildrenofthatitemor,iftheinputitem
isofatypethatcannothavechildren,thelengthofthestring
valueoftheitem.
location-setrange-to(location-set)


Range-toisaspecialfunctionintermsofthewayinwhichit
makesuseofthecontext.Foreachlocationinthecontext,it
returnsarangefromthestartpointofthecontextlocationto
theendpointfoundbyevaluatingitsparameterwiththat
contextlocation.Aspecial-purposeextensiontotheXPath
syntaxpermitstheuseofarange-toinplaceofanaxisspecifier
andnodetestinalocationpathstep.Forexample,toobtaina
rangefromtheelementwiththeID"label1"totheelementwith
theID"label2"youcanwritethefollowingcode:

xpointer(id("label1")/range-to(id("label2")))
Asanotherexample,ifportionsofadocumenthavebeen
markedbyEdStartandEdEndelements,rangescoveringall
suchpairscouldbefoundwiththefollowingcode:

xpointer(//EdStart/range-to(following::EdEnd[1])))
location-setstart-point(location-set)
Thisfunctionreturnsapointforeachlocationintheinputas
specifiedbythefollowingrules:
Foraninputpoint,theoutputelementisthesamepoint.
Foraninputrange,theoutputelementisthestartpointof
therange.
Forarootorelementnodeinput,theoutputisthepoint
justbeforethefirstchildoftheinput.Thatis,theoutput
pointhasacontainernodeoftheinputnodeandanindex
ofzero.
Foratext,comment,orprocessinginstructionnode,the
outputisthepointjustbeforethefirstcharacterofthetext
content.Thatis,theoutputpointhasacontainerofthe


inputnodeandanindexofzero.
Foranattributeornamespacenode,theXPointerinwhich
thefunctionappearsfails.
location-setstring-range(location-set,string,number?,
number?)
Foreachitemintheinputlocation-set,thefunctionsearches
thestringvalueofthatitemforthesecondparameter.Foreach
nonoverlappingoccurrencefound,itaddsarangetotheoutput
location-set.Thisrangeconsistsoftwocharacter-points
encompassingtheoccurrenceofthestringiftheoptional
numericthirdandfourthparametersareabsent.
Ifonenumericparameterispresent,thefunctionreturnsthe
positionofthefirstcharacteroftheresultingrangeadjustedby
thatparameterrelativetothebeginningofthematchedstring.
Asinglenumericparametervalueof1indicatesnoadjustment.
Ifasecondnumericparameterispresent,itspecifiesthelength
oftheresultingrangeincharacters.Thedefault,intheabsence
ofasecondnumericparameter,isthattheresultingrange
extendstoincludethelastmatchedcharacter.Ifthenumeric
parametersaresuchthattheresultingrangewouldextend
beyondeitherendofthestringvalue,theXPointerpartinwhich
thefunctionappearsfails.


6.5FunctionLibrary
AllXPathimplementationsmustincludecertaincorefunctions.
Forparticularapplications,thisfunctionlibrarymaybe
augmented.Forexample:
XMLcanonicalizationaddsthefunction"here()".(See
Chapter9.)
XPointeraddsseveralfunctionsanddatatypes.(See
Chapter7.)
Ofcourse,thevariousoperatorsthatcanappearinXPath
expressionsmayalsobeconsideredasfunctionsinvokedbythe
operator'ssyntaxratherthantheusualfunctionalsyntax.XPath
doesnotconsiderthenodetestslistedinSection6.3.3,which
looklikefunctioncalls(suchas"text()"),toactuallybe
functions.
Therestofthissectiondescribesthefunctionsinfunction
prototypeformat.Anitalicizeddatatypebeforethefunction
namegivesthetypeofoutput.Thefunctionnameappearsin
boldfacetype.Eachparameterisrepresentedbyitsitalicized
datatype.Whereaquestionmark("?")appearsaftera
parameterdatatype,itindicatesthattheparameterisoptional.

6.5.1Node-SetFunctions
Node-set-relatedfunctionsarelistedhereinalphabeticorderby
functionname,followedbyadescriptionoftheiroutput.
The"id"function,initssimplestmodewithastringparameter,andthe
"count"functionareparticularlyimportanttoXMLSecurity.


numbercount(node-set)
Thenumberofnodesintheparameter.
node-setid(object)
TheelementwithauniqueIDequaltotheparameterifthe
parameterisastring.Iftheparameterisanode-set,itconsists
ofthesetofelements,eachwithauniqueIDequaltothestring
valueofanymemberofthenode-set.Forotherparameter
types:
Theparameterisconvertedtoitsstringvalue,whichis
treatedasalistoftokensseparatedbywhitespace
TheresultisthesetofelementswithuniqueIDsequalto
anyofthosetokens
numberlast()
Anumberequaltothecontextsizeoftheexpressionevaluation
context.
stringlocal-name(node-set?)
Thelocalpartoftheexpandednameofthefirstnode,in
documentorder,intheparameternode-set.Iftheparameter
node-setisnullorifthefirstnodehasnoexpandedname,the
functionreturnsanullstring.Iftheparameterisomitted,the
functionactsasiftheparameterwereanode-setcontaining
onlythecontextnode.Forexample:

local-name(
stringname(node-set?)


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×