<spec xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax" id="spec-top" w3c-doctype="pr">
<header id="id-spec-header">
<title role="spec-conditional" id="x">XML Path Language (XPath)</title>
<version role="spec-conditional">2.0</version>
<w3c-designation>PR-xpath-20061121</w3c-designation>
<w3c-doctype>W3C Proposed Recommendation</w3c-doctype>
<pubdate><day>21</day><month>November</month><year>2006</year></pubdate>

<publoc>

<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2006/PR-xpath20-20061121/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2006/PR-xpath20-20061121/</loc>
</publoc>

<altlocs>
  
  
  <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2006/PR-xpath20-20061121/xpath20.xml" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XML</loc>
  <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2006/PR-xpath20-20061121/diff-from-20060608.html" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Recent revisions</loc>
</altlocs>

<latestloc>

<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/xpath20/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/xpath20/</loc></latestloc>

<prevlocs>
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2006/CR-xpath20-20060608/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>


<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2005/CR-xpath20-20051103/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest"/>


<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2005/WD-xpath20-20050915/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2005/WD-xpath20-20050915/</loc>


<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2005/WD-xpath20-20050404/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2005/WD-xpath20-20050404/</loc>


<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2005/WD-xpath20-20050211/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2005/WD-xpath20-20050211/</loc>


<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2004/WD-xpath20-20040723/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2004/WD-xpath20-20040723/</loc>


<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2003/WD-xpath20-20031112/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2003/WD-xpath20-20031112/</loc>


<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2003/WD-xpath20-20030822/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2003/WD-xpath20-20030822/</loc>


<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2003/WD-xpath20-20030502/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/TR/2003/WD-xpath20-20030502/</loc>


</prevlocs>

<authlist>
<author role="xpath">
<name>Anders Berglund (XSL WG)</name>

<affiliation>IBM  Research</affiliation><email xmlns:xlink="http://www.w3.org/1999/xlink" href="mailto:alrb@us.ibm.com" xlink:type="simple" xlink:show="new" xlink:actuate="onRequest">alrb@us.ibm.com</email></author>

<author>
<name>Scott Boag (XSL WG)</name>
<affiliation>IBM  Research</affiliation><email xmlns:xlink="http://www.w3.org/1999/xlink" href="mailto:scott_boag@us.ibm.com" xlink:type="simple" xlink:show="new" xlink:actuate="onRequest">scott_boag@us.ibm.com</email>

</author><author> <name>Don Chamberlin (XML Query
WG)</name>
<affiliation>IBM Almaden Research Center</affiliation>
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.almaden.ibm.com/cs/people/chamberlin/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.almaden.ibm.com/cs/people/chamberlin/</loc>
</author>

<author><name>Mary F. Fernández (XML Query
WG)</name><affiliation>AT&amp;T Labs</affiliation><email xmlns:xlink="http://www.w3.org/1999/xlink" href="mailto:mff@research.att.com" xlink:type="simple" xlink:show="new" xlink:actuate="onRequest">mff@research.att.com</email>
</author>



<author role="xpath">
<name>Michael Kay (XSL WG)</name>
<affiliation>Saxonica</affiliation>
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.saxonica.com/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.saxonica.com/</loc>
</author>

<author><name>Jonathan
Robie (XML Query WG)</name><affiliation>DataDirect Technologies</affiliation>
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.xquery.com/people/jonathan_robie/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.xquery.com/people/jonathan_robie/</loc>
</author>

<author><name>Jérôme Siméon (XML Query
WG)</name><affiliation>IBM T.J. Watson Research Center
</affiliation><email xmlns:xlink="http://www.w3.org/1999/xlink" href="mailto:simeon@us.ibm.com" xlink:type="simple" xlink:show="new" xlink:actuate="onRequest">simeon@us.ibm.com</email></author>

</authlist>

<status id="id-status">
<p><emph>This section describes the status of this document at the
time of its publication. Other documents may supersede this document.
A list of current W3C publications and the latest revision of this
technical report can be found in the <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">W3C technical reports index</loc> at
http://www.w3.org/TR/.</emph></p>

<p>This is a <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/2004/02/Process-20040205/tr.html#RecsPR" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Proposed 
Recommendation</loc>. On 3 November 2005, this specification

<phrase role="xpath"><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2005/CR-xpath20-20051103/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">was published</loc></phrase>
as a
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/2004/02/Process-20040205/tr.html#RecsCR" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Candidate
Recommendation</loc>, and a Call for Implementations was announced. On 08 June 2006, a revision

<phrase role="xpath"><loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2006/CR-xpath20-20060608/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">was published</loc></phrase> in order to give visibility to the technical decisions
that had been made in response to comments received since initial publication of the Candidate Recommendation.</p>

<p>Publication as a Proposed Recommendation does not imply
endorsement by the W3C Membership. This is a draft document and may be
updated, replaced or obsoleted by other documents at any time. It is
inappropriate to cite this document as other than work in progress.
This specification will remain a Proposed Recommendation until at
least 31 December 2006.</p>



<p>
<phrase role="xpath">This document was jointly produced by the 
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/XML/Query" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XML Query Working Group</loc> 
and the <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/Style/XSL" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XSL Working Group</loc>, 
both of which are part of the 
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/XML/Activity" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XML Activity</loc>.</phrase></p>

<p>This draft includes corrections and changes based on 

<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/Bugs/Public/buglist.cgi?query_format=advanced&amp;short_desc_type=allwordssubstr&amp;short_desc=&amp;product=XPath+%2F+XQuery+%2F+XSLT&amp;component=XPath&amp;version=Candidate+Recommendation&amp;long_desc_type=allwordssubstr&amp;long_desc=&amp;bug_file_loc_type=allwordssubstr&amp;bug_file_loc=&amp;status_whiteboard_type=allwordssubstr&amp;status_whiteboard=&amp;keywords_type=allwords&amp;keywords=&amp;bug_status=RESOLVED&amp;bug_status=VERIFIED&amp;bug_status=CLOSED&amp;emailtype1=substring&amp;email1=&amp;emailtype2=substring&amp;email2=&amp;bugidtype=include&amp;bug_id=&amp;votes=&amp;chfieldfrom=&amp;chfieldto=Now&amp;chfieldvalue=&amp;cmdtype=doit&amp;order=Reuse+same+sort+as+last+time&amp;field0-0-0=noop&amp;type0-0-0=noop&amp;value0-0-0=" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">public comments</loc> 
recorded in the W3C public Bugzilla repository 
(<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/Bugs/Public/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/Bugs/Public/</loc>) 
used for tracking issues. A list of substantive changes since the publication of the  <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/2005/CR-xpath20-20051103/" role="xpath" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Candidate Recommendation</loc> of 03 November 2005 can be found in <specref ref="id-revisions-log"/>.</p>

<p><phrase role="xpath">
This specification is designed to be referred to normatively from
other specifications defining a host language for it; it is not
intended to be implemented outside a host language.  The
implementability of this specification has been tested in the context
of its normative inclusion in host languages defined by the <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/xslt20" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XSLT 2.0</loc> and <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/TR/xquery" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">XQuery 1.0</loc> specifications;
see those specifications for implementation reports.</phrase></p>


<p>The W3C membership and other interested parties are invited to review this document 
and, through 31 December 2006,
 
to submit comments  using W3C's <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/Bugs/Public/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">public Bugzilla system</loc> 
(instructions can be found at 
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/XML/2005/04/qt-bugzilla" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://www.w3.org/XML/2005/04/qt-bugzilla</loc>). 
If access to that system is not feasible, you may send your comments to 
the W3C XSLT/XPath/XQuery public comments mailing list, 
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="mailto:public-qt-comments@w3.org" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">public-qt-comments@w3.org</loc>. 
It will be very helpful if you include the string 

<phrase role="xpath">[XPath]</phrase> 
in the subject 
line of your comment, whether made in Bugzilla or in email. Each Bugzilla 
entry and email message should contain only one comment.  Archives of the 
comments and responses are available at 
<loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://lists.w3.org/Archives/Public/public-qt-comments/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">http://lists.w3.org/Archives/Public/public-qt-comments/ </loc>.</p>
<p>Members of the W3C Advisory Committee will find the appropriate
review form for this document by consulting their <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/2002/09/wbs/myQuestionnaires" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">list of current   WBS questionnaires</loc>. Note that substantive technical comments were expected during the Last Call
review period that ended 15 February 2004.</p>

<p>This document was produced by  
<phrase role="xpath">groups</phrase> operating under the <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/Consortium/Patent-Policy-20040205/" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">5 February 
2004 W3C Patent Policy</loc>. W3C maintains a <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/2004/01/pp-impl/18797/status#disclosures" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">public list of any 
patent disclosures</loc> made in connection with the deliverables of the 
group <phrase role="xpath"> and also maintains a <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/2004/01/pp-impl/19552/status#disclosures" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">public list of any patent 
disclosures</loc> made in connection with the deliverables of the XSL 
Working Group; those pages also include</phrase> instructions for 
disclosing a patent. An individual who has actual knowledge of a patent 
which the individual believes contains <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/Consortium/Patent-Policy-20040205/#def-essential" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">Essential 
Claim(s)</loc> with respect to this specification should disclose the 
information in accordance with  <loc xmlns:xlink="http://www.w3.org/1999/xlink" href="http://www.w3.org/Consortium/Patent-Policy-20040205/#sec-Disclosure" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">section 
6 of the W3C Patent Policy</loc>.</p>
</status>

<abstract id="id-abstract"><p role="xpath">XPath 2.0 is an expression
language that allows the processing of values conforming to the data
model defined in <bibref ref="datamodel"/>. The data model provides a
tree representation of XML documents as well as atomic values such as
integers, strings, and booleans, and sequences that may contain both
references to nodes in an XML document and atomic values. The result
of an XPath expression may be a selection of nodes from the input
documents, or an atomic value, or more generally, any sequence allowed
by the data model. The name of the language derives from its most
distinctive feature, the path expression, which provides a means of
hierarchic addressing of the nodes in an XML tree. 

XPath 2.0 is a superset of <bibref ref="XPath"/>, with the added
capability to support a richer set of data types, and to take
advantage of the type information that becomes available when
documents are validated using XML Schema. A backwards compatibility
mode is provided to ensure that nearly all XPath 1.0 expressions
continue to deliver the same result with XPath 2.0; exceptions to this
policy are noted in [<specref ref="id-backwards-compatibility"/>].</p> 

</abstract>

<langusage>
<language id="EN">English</language>
<language id="ebnf">EBNF</language>
</langusage>
<revisiondesc>
<slist>
<sitem>Working Draft. (2001;06;07)</sitem>
</slist>
</revisiondesc>
</header>
<body>

<div1 id="id-introduction">

	<head>Introduction</head> 

	 

	

	<p role="xpath">The primary purpose of XPath is to address the
	nodes of <bibref ref="XML"/> or <bibref ref="XML1.1"/> trees.

	XPath gets its name from its use of a path notation for navigating through the hierarchical structure of an XML
	document.

        XPath uses a compact, non-XML syntax to facilitate use of
        XPath within URIs and XML attribute values.</p>

<p><termdef id="dt-datamodel" term="data model">XPath operates on the abstract,
	logical structure of an XML document, rather than its surface
	syntax.  This logical structure, known as the <term>data
	model</term>,  is defined in <bibref ref="datamodel"/>.</termdef></p>

	<p role="xpath">XPath is designed to be embedded in a
	<term>host language</term> such as <bibref ref="XSLT"/> or
	<bibref ref="xquery"/>. XPath has a natural subset that can be
	used for matching (testing whether or not a node matches a
	pattern); this use of XPath is described in <bibref ref="XSLT"/>.</p>

	<p>XQuery Version 1.0 is an extension of XPath Version 2.0. Any expression that is syntactically valid and
	executes successfully in both XPath 2.0 and XQuery 1.0 will
	return the same result in both languages.  Since these
	languages are so closely related, their grammars and language
	descriptions are generated from a common source to ensure
	consistency, and the editors of these specifications work
	together closely.</p>

	<p>XPath also depends on and is closely related to the
	following specifications:</p>

	<ulist>
	  <item>
            <p><bibref ref="datamodel"/> defines the data model that underlies all XPath expressions.</p>
	  </item>

	  <item>
	  <p><bibref ref="XQueryFormalSemantics"/> defines the static semantics of XPath and also
	  contains a formal but non-normative description of the
	  dynamic semantics that may be useful for implementors and others
	  who require a formal definition.</p></item>

          <item>
	  <p>The type system of XPath is based on <bibref ref="XMLSchema"/>.</p>
	  </item>

	  <item>
	  <p>The built-in function library  and the operators supported by
	  XPath are defined in <bibref ref="FunctionsAndOperators"/>.</p>
	  </item>

	  

        </ulist>
		
	
	<p>This document specifies a grammar for XPath, using the
		same basic EBNF notation used in <bibref ref="XML"/>. Unless otherwise noted (see <specref ref="lexical-structure"/>), whitespace is not significant in <phrase role="xpath">expressions</phrase>. Grammar productions are introduced together with the features that they describe, and a complete grammar is also presented in the appendix [<specref ref="nt-bnf"/>].  The appendix is the normative version.</p><p>In the grammar productions in this document, named symbols are underlined and literal text is enclosed in double quotes. For example, the following  production describes the syntax of a function call:</p><scrap headstyle="show"> 
		  <head/> 
		  <prod num="48" id="fakeid_doc-xpath-FunctionCall"><lhs>FunctionCall</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xpath-QName" xlink:type="simple">QName</nt>  "("  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-ExprSingle" xlink:type="simple">ExprSingle</nt>  (","  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-ExprSingle" xlink:type="simple">ExprSingle</nt>)*)?  ")"</rhs></prod> 
		</scrap><p>The production should be read as follows: A
		function call consists of a QName followed by an
		open-parenthesis. The open-parenthesis is followed by
		an optional argument list. The argument list (if
		present) consists of one or more expressions,
		separated by commas. The optional argument list is
		followed by a close-parenthesis. </p>

		<p>Certain aspects of language
		processing are described in this specification as
		<term>implementation-defined</term> or
		<term>implementation-dependent</term>.</p>

<ulist>
  <item>
    <p><termdef id="dt-implementation-defined" term="implementation defined"><term>Implementation-defined</term>
		indicates an aspect that may differ between
		implementations, but must be specified by the
		implementor for each particular
		implementation.</termdef></p>
  </item>
  <item>
    <p>
      <termdef id="dt-implementation-dependent" term="implementation   dependent"><term>Implementation-dependent</term>
		indicates an aspect that may differ between
		implementations, is not specified by this or any W3C
		specification, and is not required to be specified by
		the implementor for any particular
		implementation.</termdef></p>
  </item>
</ulist>

<p role="xpath">A language aspect described in this specification as
<term>implementation-defined</term> or <term>implementation
dependent</term> may be further constrained by the specifications of a
host language in which XPath is embedded.</p>

<p>This document normatively defines the dynamic semantics of
XPath. The static semantics of XPath are normatively defined
in <bibref ref="XQueryFormalSemantics"/>. In this document, examples
and material labeled as "Note" are provided for explanatory purposes
and are not normative.</p></div1>


<!--
====================================================================
 $Log: xpath20.xml,v $
 Revision 1.1  2006/11/22 08:53:42  jean-gui
 TR/2006/PR-xpath20-20061121

 Revision 1.61  2006/11/09 15:19:34  NormanWalsh
 Updated by Norm and Don

 Revision 1.58  2005/10/25 20:27:38  sboag
 Removed role-"parse-test" from element that holds a clearly incomplete expression.

 Revision 1.57  2005/10/21 04:27:02  sboag
 Don's latest changes.

 Revision 1.56  2005/09/01 20:36:35  NormanWalsh
 Edits from Don

 Revision 1.55  2005/07/27 02:47:41  sboag
 Added a validate of the unassembled doc for target xquery.html, as a sanity check,
 Removed <nt> brackets around QName and NCName, since the don't work and
 I'm not sure how to fix them, of if they should be fixed, at the moment, and
 added xpath- prefix to to id's that were xpath only, but had xquery equivelents
 elsewhere (escapeQuot and escapeAPos).

 Revision 1.54  2005/07/10 07:13:41  sboag
 July 10 draft.

 Revision 1.52  2005/07/08 16:53:30  sboag
 Don's latest edits.  See changes.txt for details.

 Revision 1.51  2005/03/28 14:16:14  NormanWalsh
 Updates from DC

 Revision 1.42  2004/10/26 17:23:48  NormanWalsh
 Pubrules tweaks

 Revision 1.41  2004/10/18 14:56:39  sboag
 Don's checkin.  See changes.txt (1.5) for this checkin for more info.

 Revision 1.40  2004/07/14 21:02:20  NormanWalsh
 Updated function/datatype namespaces; tweaked status; 23 July draft, pubrules clean

 Revision 1.39  2004/07/13 12:20:39  NormanWalsh
 Log update, I think. Not signficant anyway.

 Revision 1.35  2004/06/07 08:27:13  sboag
 Change of Validation stuff, according to request note from Don.

 Revision 1.33  2004/05/31 18:32:21  sboag
 Latest grammar changes, part of last call comments response.  (Sorry for lack
 of fine-grained detail, but CVS has been down for a week.)  The EBNF is a proposal,
 with change markings.

 Revision 1.31  2004/05/14 20:15:52  sboag
 Latest integration effort between Don and Scott.

 Revision 1.27  2003/12/05 01:04:09  sboag
 Change name of Predicates production to PredicateList.  Approved at Oracle F2F, 11/5/03

 Revision 1.26  2003/12/04 21:54:00  sboag
 Global search-replace: DC requests to change the production-names of
 SchemaMode and SchemaContext to ValidationMode and ValidationContext, to more closely match the explanatory text. Editorial change only. Names of other related productions (SchemaContextLoc etc.) remain unchanged.

 Revision 1.25  2003/12/04 16:45:21  sboag
 Change FilterStep to FilterExpr as per http://lists.w3.org/Archives/Member/w3c-xsl-query/2003Nov/0014.html

 Revision 1.24  2003/11/07 01:58:07  NormanWalsh
 Added xpath-dt-static-typing-feature link

 Revision 1.23  2003/11/04 19:23:32  NormanWalsh
 Added required class attributes; added new informative bibl entries

 Revision 1.22  2003/10/30 04:25:50  sboag
 Changed ComputedXMLComment to CompXMLComment, as per http://lists.w3.org/Archives/Public/public-qt-comments/2003Oct/0056.html (editorial discretion taken)

 Revision 1.21  2003/10/28 19:29:20  NormanWalsh
 Tweaked document order per Jeni

 Revision 1.20  2003/10/28 19:25:16  NormanWalsh
 Ran through crlf to get rid of DOS line breaks...sigh.

 Revision 1.19  2003/10/28 13:55:28  NormanWalsh
 Final edits from Don

 Revision 1.16  2003/08/27 01:52:17  sboag
 Fed through dos2unix, to clean up extra CRs.

 Revision 1.15  2003/08/13 18:31:47  NormanWalsh
 Updates from Don on 7 Aug

 Revision 1.13  2003/07/31 18:09:48  sboag
 Don's latest edits, along with the module namespace changed originally outlined in http://lists.w3.org/Archives/Member/w3c-xml-query-wg/2003Jul/0218.html, and approved by XQuery July 30.

 Revision 1.12  2003/07/22 17:59:09  sboag
 Reduce production names to max 20:
 Original Name	Len	New Name	Len
 MustUnderstandExtension	23	MUExtension	11
 QuoteAttributeContentChar	25	QuotAttrContentChar	18
 AposAttributeContentChar	24	AposAttrContentChar	18
 AbbreviatedForwardStep	22	AbbrevForwardStep	17
 AbbreviatedReverseStep	22	AbbrevReverseStep	17
 ComputedDocumentConstructor	27	CompDocConstructor	18
 ComputedElementConstructor	26	CompElemConstructor	19
 ComputedAttributeConstructor	28	CompAttrConstructor	19
 ComputedNamespaceConstructor	28	LocalNamespaceDecl	17
 ComputedXmlProcessingInstruction	32	CompPIConstructor	9
 ComputedTextConstructor	23	CompTextConstructor	19
 XmlProcessingInstruction	24	DirPIConstructor	5
 QuoteAttributeValueContent	26	QuotAttrValueContent	20
 AposAttributeValueContent	25	AposAttrValueContent	20
 ProcessingInstructionTest	25	PITest	6
 SchemaContextLocation	21	SchemaContextLoc	16
 
 Revision 1.11  2003/07/22 14:26:31  sboag
 Latest edits from Don.  Pre production name reduction.

 Revision 1.10  2003/07/08 15:59:35  sboag
 Fixed 2 obvious expression bugs.

 Revision 1.9  2003/07/01 15:21:19  sboag
 Fixed validation, which includes fixing LF problems, termref/termdef attribute mess, and nt fixes.  (stylesheet fix needs to come with this).

 Revision 1.8  2003/06/30 16:18:23  sboag
 Fix double-dash problems inside comments that Mary entered.

 Revision 1.7  2003/06/26 02:37:00  mfernand

 June 25, 2003 - Mary

 Changes to documents:
 =========================
   Modified files:
     lang/XPathXQuery.xml
     lang/expressions.xml
     lang/introduction.xml
     lang/query-prolog.xml
     lang/shared.html
     lang/xquery.html
     lang/xpath.html

   Added file:
     lang/errors.xml

   o Added markup for error definitions and references in all sections.

     - Error definitions are in new file: lang/errors.xml.

   o Added term definitions and references.

     - Additions required some minor editing to sentences/paragraphs so
       that term definitions were self-contained in Glossary.

     - All term definitions in Secs 1 & 2 should be complete.

       Exceptions: definitions of "Optional Features" are not pithy, thus
       not amenable to definition in a glossary.

     - All references in Secs 1 - 4 to terms defined in Secs 1 and 2
       are marked-up.

     - A smattering of term definitions in Secs 3 & 4 are done.
       Whomever continues with term markup should begin here.

     NB: I did not add any new term definitions - - I simply converted as
     many <term> elements as possible to <termdef>s or <termref>s.
     I did not change any term definitions other than to make them
     self-contained.

 Known styling problems (need help from Norm):
 =============================
   o Need to add "spec" attribute to <termdef> to scope term
     definitions within a particular document (e.g., "XP" or "XQ")

     - Current bug: terms that should only be defined in XQuery book
       also appear in XPath book.

   o Glossary should probably be emitted in alphabetic order.

   o Not sure what to do about errors of this kind:

     "style/issues-spec.xsl:248:20: Warning! Cannot point to resolved
     issue: #xquery-abstract-syntax"

 Issues/Questions:
 =============================
   o Should Glossary be labeled as normative?

   o Should Summary of Error Codes be labeled as normative?

 Revision 1.6  2003/06/12 22:31:50  jrobie

 Made the documents consistent with the following grammar changes:

 (a) Use "declare" consistently in prolog (replacing "define") and get
 rid of all uses of "=" except between prefix and URI. See Issue
 547. Changed terminology accordingly - "function definitions" are now
 "function declarations", "user-defined functions" are now
 "user-declared functions", etc.


 (b) Limit comments, pragmas, and extensions to places inside XQuery
 expressions where insignificant whitespace is allowed. See Issue 550.

 (c) Change if-expr so both then-clause and else-clause take ExprSingle,
 not Expr. See Query/May/0006.

 (d) New clause in Prolog: "declare" "base-uri" StringLiteral
 Scope is the module in which it is declared. Proposed by M. Rys in
 Query/Apr/0001 and adopted by Query WG telcon, 5/7/03.


 (h) Change "." to be a primary expr rather than an abbreviated step.
 See http://lists.w3.org/Archives/Member/w3c-xsl-query/2003Apr/0200.html.

 (i) Change to PITest so it allows an NCName as well as a
 StringLiteral, as proposed by JR.
 See http://lists.w3.org/Archives/Member/w3c-xsl-query/2003Apr/0256.html.

 (16) Change to Prolog syntax: function declarations can now be mixed
 with variable and other declarations. Approved, Query WG F2F, 5/16/03.

 Revision 1.5  2003/06/10 20:53:47  jrobie
 Processing model diagrams.

 Revision 1.4  2003/06/10 20:48:09  jrobie
 *** empty log message ***

 Revision 1.3  2003/04/18 22:01:52  NormanWalsh
 Editorial nits for pubrules

 Revision 1.2  2003/04/18 19:22:04  sboag
 Don's latest revisions, responding to comments from the working groups.

 Revision 1.1  2003/04/07 22:18:05  sboag
 Initial checkin of language build and parser build.

 Revision 1.29  2002/11/07 21:45:36  sboag
 Integrated new XSL from http://www.w3.org/2002/xmlspec/html/1.4/xmlspec.xsl,
 Fixed a couple minor bugs that this helpful stylesheet flagged.

 Revision 1.28  2002/11/07 19:30:56  sboag
 changed to 2.2 xmlspec, and deleted all xmlspec-v21.xxx.  Fixed BNF
 problem with OcurrenceIndicator.  Fixed prevdoc problem.

 Revision 1.27  2002/11/07 00:27:14  sboag
 Minor changes specified by today's editorial meeting, dictated by Don to me over the phone.

 Revision 1.24  2002/11/05 16:18:45  sboag
 Minor parse test fixes.

 Revision 1.23  2002/11/05 16:13:01  sboag
 Don's final Nov. 15 drafts.

 Revision 1.20  2002/08/14 16:06:35  sboag
 Fixed up example URLs to use example.org.

 Revision 1.18  2002/08/12 03:02:22  sboag
 Fixed problems with comments from previous check-in.

 Revision 1.17  2002/08/12 02:40:48  sboag
 Check for role="parse-test" for all legitimate expression examples.  ***status: Did the best I could with <code> and <eg> examples.
 -> fixed discovered bug in grammar where document {...} constructor did not work.
 -> fixed bug with processing instruction content... I had to add a PROCESSING_INSTRUCTION_CONTENT state.
 -> fixed minor bug with end tag not being closed in expressions.xml (ugh, took me 30 minutes to track down).
 -> in section on "Other Constructors", broke samples into separate <eg>s, so they will parse (otherwise they expect an operator between them).
 -> fixed problem with CDataSection outside of element content.  (...if PI, XMLComments work, so should CDataSection, I guess).
 -> broke some/every examples in section on "Quantified Expressions" into two <eg> tags, since they can process sequentially.
      -> Also had to conditionalize these examples for XPath, so that the TypeDeclaration wasn't
           used (actually, it seems useless here).
 -> Fixed many problems with "validate".  However, see note on '"validate" seems to be reserved'.  Two of the fragments currently won't parse.

 Revision 1.15  2002/08/10 22:01:47  sboag
 Changed "default collation at" to "default collation ="

 Revision 1.14  2002/08/04 21:06:21  sboag
 The following changes from the last F2F:

 (1) Delete "precedes" and "follows" operators from OrderComp.

 (2) Change name of TypeAssertion production to TypeDeclaration.

 (3) Add the following new production:

 DefaultCollationDecl ::= "default" "collation" StringLiteral

 (A collation is identified by a URI, so you can use a more specific symbol in place of StringLiteral that indicates that a URI is expected, if you want to.)

 (4) Delete the production for ResultTypeDecl.

 (5) QueryProlog should now include DefaultCollationDecl but not ResultTypeDecl, as follows:

 QueryProlog ::= (NamespaceDecl | DefaultNamespaceDecl | SchemaImport | XMLSpaceDecl
    | DefaultCollationDecl)* FunctionDefn*

 Revision 1.13  2002/07/28 19:53:05  sboag
 Don's new documents.

 Revision 1.12  2002/07/04 18:29:22  sboag
 Simply made prerecap ref refer to itself.  This was a regression, because at one
 point I had deleted this production.

 Revision 1.11  2002/06/28 09:02:07  sboag
 Merged Don's latest work with new grammar proposal.  Changes too numerous
 to detail.

 Revision 1.10  2002/04/24 22:48:30  sboag
 Fixed minor problem with lists-within-lists-within-paragraphs.

 Revision 1.9  2002/04/24 22:21:18  sboag
 Don's changes assigned to him by this morning's telcon.

 Revision 1.8  2002/04/24 02:48:08  sboag
 CSS, HTML, Link validation passes.  Parser tests pass.  Updated to target
 pub date of April 30.

 Revision 1.6  2002/04/23 17:20:33  sboag
 Removed DocumentElement from production 61, as per WG decision.
 Fixed Dana's company and email address.
 Added section on reserved words (list is mechanically generated).
 Addressed the following issues in the lexical section from
 (http://lists.w3.org/Archives/Public/www-xml-query-comments/2002Jan/0002.html),
 lengthy Michael Dyck.  Not all issues have been addressed yet.
 <item priority="2" status="done"> <description>para 1: "Whitespace may be
 		  freely added within patterns" What do you mean by "patterns"? Presumably,
 		  you're either talking about adding the symbol 'Whitespace' to grammar
 		  productions, or adding whitespace (i.e., sequences of characters) to queries.
 		  Don't confuse the two.</description></item>
 <item priority="2" status="done"> <description>"before or after any
 		  token" But you never actually define what a token is. It's not even clear what
 		  the set of token-types is. (Is it the set of left-hand-sides of producbtions 75
 		  through 216? Is it the set of symbols that appear in the "tokens" column of the
 		  TRANITION STATES table? The two are different, and both contain symbols that
 		  probably shouldn't be considered token-types.)</description></item>
 <item status="done"> <description>para 1 and bullets 1 and 2: Note that
 		  the Whitespace symbol derives the empty string, but phrases like "must always
 		  be followed by whitespace" and "whitespace may not occur" obviously mean
 		  "whitespace" in the sense of "a non-empty string of whitespace-characters". I
 		  think this shows correct usage, and there's no reason for Whitespace to be
 		  nullable. (That is, it should be the same as S.)</description></item>
 <item status="done"> <description>bullet 3: "A space" We're interested in
 		  whitespace, not just a space.</description></item>
 <item status="done"> <description>"may be significant" Don't tell us that
 		  it *may* be significant. Tell us exactly when it *is*
 		  significant.</description></item>
 <item status="done"> <description>para 2: "Tokens may be often only
 		  recognized" "may be often only" is clunky.</description></item>
 <item status="done"> <description>"in a specific state" You haven't
 		  defined states yet.</description></item>
 <item status="done"> <description>"within the evaluation": Does
 		  evaluation of a query include its parsing/lexing?</description></item>
 <item status="done"> <description>"may cause the grammar to transition to
 		  a different state" Grammars don't have states or transitions. Automata
 		  do.</description></item>
 <item status="done"> <description>"following the enumeration of tokens"
 		  Change "tokens" to "token-types".</description></item>
 <item status="done"> <description>para 3: "When tokenizing, the longest
 		  possible token is always returned" Issue 109 says this means "the longest
 		  sequence that would form a token in the token-space of the grammar, not the
 		  longest that would be valid in the current syntactic context." Does
 		  it?</description></item>
 <item status="done"> <description>"If there is an ambiguity between two
 		  tokens, ..." Presumably, you mean an ambiguity that isn't resolved by the
 		  longest-match rule.</description></item>
 <item status="done"> <description>"the token that an lower grammar
 		  number" Change "an" to "a".</description></item>
 <item status="done"> <description>is more specific than" Why do we care
 		  which is "more specific"? We want to know which is the right one. I'll assume
 		  that's what you mean.</description></item>

 Revision 1.5  2002/04/22 15:23:24  sboag
 Don says: I believe that these drafts contain all the substantive comments
 that were raised at the Cambridge task force meetings and subsequent
 telcons. These are the drafts that will be reviewed for publication. Additional
 minor editorial changes may be made before the documents are actually
 submitted to w3c.

 Revision 1.1  2002/04/01 20:10:30  sboag
 Jonathan Robie changes, including removal of fragment.xml and inclusion of
 expressions.xml, etc.
 Merge of his grammar with latest.


 Revision 1.42  2001/12/17 20:27:29  sboag
 Fixes for every-header-has-to-have-an-id.

 Revision 1.41  2001/12/16 06:31:59  sboag
 Minor fix to the comment ednote.

 Revision 1.37  2001/12/14 20:47:43  sboag
 Fixed some bad links.

 Revision 1.36  2001/12/14 17:21:26  sboag
 Fixed link.

 Revision 1.28  2001/12/11 17:09:44  sboag
 Don's suggested modifications to the grammar.  Also temporarily commented
 out the pathx1 build, 'till I get it fixed.

 Revision 1.27  2001/12/10 02:45:49  sboag
 Fixed some of the code examples that read <p><code>some example</code></p>.

 Revision 1.25  2001/12/09 22:07:16  sboag
 Fixed problem with comments from previous checkin.

 Revision 1.24  2001/12/09 21:39:37  sboag
 [batch checkin] Added {- - comment - -} type comments.  Added ";" list 
 query processing.  Added some stuff for ^char handling in reg 
 expressions, in order to support CharData better, but backed 
 out of this (but left some of the support in.  Removed old type def 
 and group stuff (can look to previous versions if we want to add this 
 back in).  Changed to case sensitivity in grammar, and updated 
 fragment.xml.  Added optional (AT schemaLocation)? to SchemaImport.  
 Other minor changes in support of WG decisions.

 Revision 1.23  2001/12/08 15:15:25  sboag
 Jonathan and Scott tweaked paragraph about QName escape.

 Revision 1.22  2001/12/07 23:34:28  sboag
 Add note about escaping QNames in the Basics section, pending resolution
 of the issue about what to do about possible EQName token.  Don needs to review.
 Removed paragraph again about enclosed expressions in element constructors. 

 Revision 1.20  2001/12/07 08:55:45  sboag
 Made rule about space before "<" be xquery spec only.

 Revision 1.19  2001/12/07 08:29:26  sboag
 Added ednote about space before "<" rule.

 Revision 1.18  2001/12/07 08:19:17  sboag
 Add <{foo}/> syntax, as per direction of XQuery WG.  Need to check about the
 enclosed expression syntax for attribute names, which I also added.

 Revision 1.17  2001/12/07 07:36:15  sboag
 Fix data-type section for XPath (remove Typeswitch, CaseClause).

 Revision 1.16  2001/12/07 07:06:38  sboag
 Changed BuiltInType to SimpleType in grammar and text.
 Removed Remove *:*.
 Defined IntegerLiteral, DecimalLiteral, and DoubleLiteral.
 Took a shot at fixing the "-" lexical rule in arithmatic section.
 Defined IntegerLiteral, DecimalLiteral, and DoubleLiteral. 

==================================================================== 
-->
<!-- 

float*date

send a value to a function that is expecting a node

"make a list of the errors that can be determined statically"

-->
<div1 id="id-basics"> 
  <head>     Basics</head> 
	 <p>The basic  building block of XPath is the
	 <term>expression</term>, which is a string of <bibref ref="Unicode"/> characters (the version of Unicode to be used is <termref def="dt-implementation-defined">implementation-defined</termref>.)
	 The language provides several kinds of expressions which may be constructed
	 from keywords, symbols, and operands. In general, the operands of an expression
	 are other expressions. XPath allows expressions to be nested with full
generality. </p> 
	 <note><p>This specification contains no 
assumptions or requirements regarding the character set encoding of strings 
of <bibref ref="Unicode"/> characters.</p></note><p>Like XML, XPath is a case-sensitive language. Keywords in
	 XPath use lower-case characters and are not reserved—that is, names in XPath expressions are allowed to be the same as language keywords, except for certain unprefixed function-names listed in <specref ref="id-reserved-fn-names"/>.</p> 
	  
	 <p><termdef term="value" id="dt-value">In the <termref def="dt-datamodel">data model</termref>, a <term>value</term> is always a <termref def="dt-sequence">sequence</termref>.</termdef> <termdef id="dt-sequence" term="sequence">A
<term>sequence</term> is an ordered collection of zero or more
<termref def="dt-item">items</termref>.</termdef>
<termdef id="dt-item" term="item">An
	 <term>item</term> is either an <termref def="dt-atomic-value">atomic value</termref> or a <termref def="dt-node">node</termref>.</termdef>
<termdef id="dt-atomic-value" term="atomic value">An <term>atomic
	 value</term> is a value in the value space of an <term>atomic
	 type</term>, as defined in <bibref ref="XMLSchema"/>.</termdef>
<termdef id="dt-node" term="node">A <term>node</term> is an instance of one of the
	  <term>node kinds</term> defined in <bibref ref="datamodel"/>.</termdef>
Each node has a unique <term>node identity</term>, a <term>typed value</term>, and a <term>string value</term>. In addition, some nodes have a <term>name</term>. The <term>typed value</term> of a node is a sequence
	 of zero or more atomic values. The <term>string value</term> of a node is a
	 value of type <code>xs:string</code>. The <term>name</term> of a node is a value of type <code>xs:QName</code>.</p> 
	 <p><termdef id="dt-singleton" term="singleton">A sequence containing exactly one item is called a
	 <term>singleton</term>.</termdef> An item is identical to a singleton sequence
	 containing that item. Sequences are never nested—for example, combining the
	 values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2,
	 3). <termdef id="dt-empty-sequence" term="empty sequence">A sequence containing zero items is called an <term>empty sequence</term>.</termdef></p>
	  <p><termdef id="dt-data-model-instance" term="XDM instance">The term <term>XDM instance</term> is used, synonymously with the term <term>value</term>, to denote an unconstrained sequence of <termref def="dt-node">nodes</termref> and/or <termref def="dt-atomic-value">atomic values</termref> in the <termref def="dt-datamodel">data model</termref>.</termdef> </p><p>Names in XPath are called <term>QNames</term>, and conform to the syntax in <bibref ref="XMLNAMES"/>. <termdef id="dt-qname" term="QName">Lexically, a <term>QName</term> consists of an optional namespace prefix and a local name. If the namespace prefix is present, it is separated from the local name by a colon.</termdef> A lexical QName can be converted into an <term>expanded QName</term> by resolving its namespace prefix to a namespace URI, using the <termref def="dt-static-namespaces">statically known namespaces</termref> <errorref code="0081" class="ST"/>. <termdef id="dt-expanded-qname" term="expanded QName">An <term>expanded QName</term> consists of an optional namespace URI and a local name. An expanded QName also retains its original namespace prefix (if any), to facilitate casting the expanded QName into a string.</termdef> The namespace URI value is 
whitespace normalized according to the rules for the <code>xs:anyURI</code> type in <bibref ref="XMLSchema"/>. Two expanded QNames are equal if their namespace URIs are equal and their local names are equal (even if their namespace prefixes are not equal). Namespace URIs and local names are compared  on a codepoint basis, without further normalization.</p><p><phrase role="xpath">This document uses the following namespace prefixes to represent the namespace URIs with which they are listed. Use of these namespace prefix bindings in this document is not normative.</phrase></p>  <ulist><item><p><code>xs = http://www.w3.org/2001/XMLSchema</code></p></item><item><p><code>fn = http://www.w3.org/2005/xpath-functions</code></p></item><item role="xpath"><p><code>err = http://www.w3.org/2005/xqt-errors</code> (see <specref ref="id-identifying-errors"/>).</p></item></ulist> 
	 <p>Element nodes have a property called <term>in-scope namespaces</term>. <termdef term="in-scope namespaces" id="dt-in-scope-namespaces">The <term>in-scope namespaces</term> property of an element node is a set of <term>namespace bindings</term>, each of which associates a namespace prefix with a URI, thus defining the set of namespace prefixes that are available for interpreting QNames within the scope of the element. For a given element, one namespace binding may have an empty prefix; the URI of this namespace binding is the default namespace within the scope of the element.</termdef></p><p role="xpath">In <bibref ref="XPath"/>, the in-scope namespaces of an element node are represented by a collection of <term>namespace nodes</term> arranged on a <term>namespace axis</term>. In XPath Version 2.0, the namespace axis is deprecated and need not be supported by a host language. A host language that does not support the namespace axis need not represent namespace bindings in the form of nodes.</p><p><termdef term="URI" id="dt-URI">Within this specification, the term <term>URI</term> refers to a Universal Resource Identifier as
defined in <bibref ref="RFC3986"/> and extended in <bibref ref="RFC3987"/> with the new name <term>IRI</term>.</termdef>  The term URI has been retained in preference to IRI to avoid introducing new names for concepts such as "Base URI" that are defined or referenced across the whole family of XML specifications.</p><div2 id="context"> 
		<head>Expression Context</head> 
		<p><termdef id="dt-expression-context" term="expression context">The <term>expression context</term> for a given expression consists of
		all the information that can affect the result of the expression.</termdef> This
		information is organized into two categories called
	 the <termref def="dt-static-context">static
		context</termref> and the <termref def="dt-dynamic-context">dynamic context</termref>.</p> 
		 
		<div3 id="static_context"> 
		  <head>Static Context</head> 
		  <p><termdef id="dt-static-context" term="static context">The <term>static context</term> of an expression is
		  the information that is available during static analysis of the expression, prior
		  to its evaluation.</termdef> This information can be used to decide whether the
		  expression contains a <termref def="dt-static-error">static error</termref>.
		  If analysis of an 
expression relies on some component of the <termref def="dt-static-context">static context</termref> that has not been 
assigned a value, a <termref def="dt-static-error">static
		  error</termref> is raised <errorref code="0001" class="ST"/>.</p> 
		  <p>The individual components of the <termref def="dt-static-context">static context</termref> are summarized below. <phrase role="xpath">A default initial value for each component may be specified by the host language. The scope of each component is specified in <specref ref="id-xp-static-context-components" role="xpath"/>.</phrase> </p> 
		   
		  <ulist> 
			 <item><p><termdef id="dt-xpath-compat-mode" term="XPath 1.0 compatibility     mode"><term>XPath 1.0 compatibility
			 mode.</term>  <phrase role="xpath">This value is <code>true</code> if rules for backward compatibility with XPath Version 1.0 are in effect; otherwise it is <code>false</code>.</phrase></termdef></p></item> 
			 <item> 
				<p><termdef id="dt-static-namespaces" term="statically known namespaces"><term>Statically known namespaces.</term> This is a set of (prefix,
				URI) pairs that define all the namespaces that are known during static processing of a given expression.</termdef> The URI value is 
whitespace normalized according to the rules for the <code>xs:anyURI</code> type in <bibref ref="XMLSchema"/>. Note the difference between <termref def="dt-in-scope-namespaces">in-scope namespaces</termref>, which is a dynamic property of an element node, and <termref def="dt-static-namespaces">statically known namespaces</termref>, which is a static property of an expression.</p> 
			 </item> 
			 <item> 
				<p><termdef id="dt-def-elemtype-ns" term="default element/type namespace"><term>Default element/type namespace.</term> This is a
				namespace URI or "none". The namespace URI, if present, is used for any unprefixed QName appearing in a
				position where an element or type name is expected.</termdef> The URI value is 
whitespace normalized according to the rules for the <code>xs:anyURI</code> type in <bibref ref="XMLSchema"/>.</p> 
			 </item> 
			 <item> 
				<p><termdef id="dt-def-fn-ns" term="default function namespace"><term>Default function namespace.</term> This is a
				namespace URI or "none". The namespace URI, if present, is used for any unprefixed QName appearing in a position where a function name is expected.</termdef> The URI value is 
whitespace normalized according to the rules for the <code>xs:anyURI</code> type in <bibref ref="XMLSchema"/>.</p> 
			  </item> 
			 <item> 
				<p><termdef id="dt-issd" term="in-scope schema definitions"><term>In-scope schema
			 definitions.</term> This is a generic term
			 for all the element declarations, attribute declarations, and schema type
			 definitions that are in scope during
			 processing of an expression.</termdef> It includes the
			 following three
			 parts:</p><ulist><item><p>

			        <termdef id="dt-is-types" term="in-scope schema type"><term>In-scope schema types.</term> Each schema type
			        definition is identified either by an <termref def="dt-expanded-qname">expanded
			        QName</termref> (for a <term>named type</term>)
			        or by an <termref def="dt-implementation-dependent">implementation-dependent</termref> type
			        identifier (for an <term>anonymous
			        type</term>). The in-scope schema types include the predefined schema types described in <specref ref="id-predefined-types"/>.

                                

                         </termdef></p>

</item>


<item><p><termdef id="dt-is-elems" term="in-scope element declarations"><term>In-scope element declarations.</term> Each element
declaration is identified either by an <termref def="dt-expanded-qname">expanded QName</termref> (for a top-level element
declaration) or by an <termref def="dt-implementation-dependent">implementation-dependent</termref> element identifier (for a
local element declaration). </termdef> An element
declaration includes information about the element's <termref def="dt-substitution-group">substitution group</termref> affiliation.</p><p><termdef term="substitution group" id="dt-substitution-group"><term>Substitution groups</term> are defined in <bibref ref="XMLSchema"/> Part 1,  Section 2.2.2.2. Informally, the substitution group headed by a given element (called the <term>head element</term>) consists of  the set of elements that can be substituted for the head element without affecting the outcome of schema validation.</termdef></p></item><item><p><termdef id="dt-is-attrs" term="in-scope attribute declarations"><term>In-scope attribute
declarations.</term> Each attribute declaration is identified either
by an <termref def="dt-expanded-qname">expanded QName</termref> (for a top-level attribute declaration) or by an
<termref def="dt-implementation-dependent">implementation-dependent</termref> attribute identifier (for a local attribute
declaration).  </termdef></p></item></ulist> </item> <item> <p>
<termdef id="dt-in-scope-variables" term="in-scope variables"><term>In-scope variables.</term> This is a set of (expanded QName, type) pairs. It defines the
set of variables that are available for reference within an
expression. The <termref def="dt-expanded-qname">expanded QName</termref> is the name of the variable, and the type is the
<termref def="dt-static-type">static type</termref> of the
variable.</termdef></p><p> An expression that binds a variable (such as a
 <code>for</code>,
<code>some</code>, or <code>every</code> expression) extends the
<termref def="dt-in-scope-variables">in-scope variables</termref> of its subexpressions with the new bound variable
and its type. </p>
				 
			 </item><item><p><termdef term="context item static type" id="dt-context-item-static-type"><term>Context item static type.</term> This component defines the <termref def="dt-static-type">static type</termref> of the context item within the scope of a given expression.</termdef></p></item> 
			 <item> 
				<p><termdef id="dt-function-signature" term="function signature"><term>Function signatures.</term> This component defines the set of functions that are available
				to be called from within an
			 expression. Each function is uniquely
			 identified by its <termref def="dt-expanded-qname">expanded QName</termref> and its arity (number
			 of parameters).</termdef> In addition to the name and arity, each function signature specifies the <termref def="dt-static-type">static types</termref> of the function parameters and  result.</p>

                         <p>The <termref def="dt-function-signature">function signatures</termref> include the signatures of <termref def="dt-constructor-function">constructor functions</termref>, which are
                         discussed in <specref ref="id-constructor-functions"/>.</p>

			 </item> 
			 <item> 
				<p> <termdef id="dt-static-collations" term="statically known collations"><term>Statically known collations.</term> This is an <termref def="dt-implementation-defined">implementation-defined</termref> set of (URI,
				collation) pairs. It defines the names of the collations that are available for
				use in processing  expressions.</termdef> <termdef term="collation" id="dt-collation">A <term>collation</term> is a specification of the manner in which strings and URIs are compared and, by extension, ordered. For a more complete definition of collation, see <bibref ref="FunctionsAndOperators"/>.</termdef></p> 
			 </item> 
			 <item> 

				<p> <termdef id="dt-def-collation" term="default collation"><term>Default
				collation.</term> This identifies one of the collations in <termref def="dt-static-collations">statically known collations</termref> as the  collation to be
				used by functions and operators for comparing and ordering values of type <code>xs:string</code> and <code>xs:anyURI</code> (and types derived from them) when no
				explicit collation is
				specified.</termdef></p>

			 </item> 
			 <item> 
		<p><termdef id="dt-base-uri" term="base URI"><term>Base URI.</term> This is an absolute URI, used when necessary in the resolution of relative URIs (for example, by the <code>fn:resolve-uri</code> function.)</termdef> The URI value is 
whitespace normalized according to the rules for the <code>xs:anyURI</code> type in <bibref ref="XMLSchema"/>.</p> 
			 </item>
<item><p> <termdef id="dt-known-docs" term="statically known  documents"><term>Statically known documents.</term> This is a mapping
from strings onto types.  The string represents the absolute URI of a
resource that is potentially available using the <code>fn:doc</code>
function.  The type is the <termref def="dt-static-type">static type</termref> of a call to <code>fn:doc</code>  with the given URI as its
literal argument. </termdef> 
If the argument to <code>fn:doc</code> is a
string literal that is not present in <term>statically known documents</term>, then the
<termref def="dt-static-type">static type</termref> of
<code>fn:doc</code> is <code>document-node()?</code>.</p>
<note><p>The purpose of the <term>statically known
documents</term> is to provide static type information, not to determine
which documents are available. A URI need not be found in the
<term>statically known documents</term> to be accessed using
<code>fn:doc</code>. </p></note>
</item>

<item><p><termdef id="dt-known-collections" term="statically known  collections"><term>Statically known collections.</term> This is a
mapping from strings onto types.  The string represents the absolute
URI of a resource that is potentially available using the
<code>fn:collection</code> function.  The type is the type of the
sequence of nodes that would result from calling the
<code>fn:collection</code> function with this URI as its
argument.</termdef> If the argument to
<code>fn:collection</code> is a string literal that is not present in
<term>statically known collections</term>, then the <termref def="dt-static-type">static type</termref> of
<code>fn:collection</code> is <code>node()*</code>.</p><note><p>The purpose of the <term>statically known
collections</term> is to provide static type information, not to determine
which collections are available. A URI need not be found in the
<term>statically known collections</term> to be accessed using
<code>fn:collection</code>. 
</p></note></item><item><p><termdef id="dt-known-default-collection" term="statically known default collection type"><term>Statically known default collection type.</term> This is the type of the sequence of nodes that would result from calling the <code>fn:collection</code> function with no arguments.</termdef> Unless initialized to some other value by an implementation, the value of <term>statically known default collection type</term> is <code>node()*</code>.</p></item>
</ulist> 


</div3>
<div3 id="eval_context"> <head>Dynamic Context</head> <p><termdef id="dt-dynamic-context" term="dynamic context">The <term>dynamic
context</term> of an expression is defined as information that is
available at the time the expression is evaluated.</termdef> If
evaluation of an expression relies on some part of the <termref def="dt-dynamic-context">dynamic context</termref> that has not been
assigned a value, a <termref def="dt-dynamic-error">dynamic
error</termref> is raised <errorref class="DY" code="0002"/>.</p><p>The individual
components of the <termref def="dt-dynamic-context">dynamic
context</termref> are summarized below. Further rules governing the
semantics of these components can be found in <specref ref="id-xp-evaluation-context-components" role="xpath"/>.</p><p>The
<termref def="dt-dynamic-context">dynamic context</termref> consists
of all the components of the <termref def="dt-static-context">static
context</termref>, and the additional components listed below.</p>
<p><termdef id="dt-focus" term="focus">The first three components of
the <termref def="dt-dynamic-context">dynamic context</termref>
(context item, context position, and context size) are called the
<term>focus</term> of the expression. </termdef> The focus enables the
processor to keep track of which items are being processed by the
expression.</p> <p>Certain language constructs, notably the <termref def="dt-path-expression">path
expression</termref> <code role="parse-test">E1/E2</code> and the <termref def="dt-predicate">predicate</termref> <code role="parse-test">E1[E2]</code>, create a new focus
for the evaluation of a sub-expression. In these constructs, <code role="parse-test">E2</code> is evaluated once for each item in the
sequence that results from evaluating <code role="parse-test">E1</code>. Each time <code role="parse-test">E2</code> is evaluated, it is evaluated with a
different focus. The focus for evaluating <code role="parse-test">E2</code> is referred to below as the <term>inner
focus</term>, while the focus for evaluating <code role="parse-test">E1</code> is referred to as the <term>outer
focus</term>. The inner focus exists only while <code role="parse-test">E2</code> is being evaluated. When this evaluation
is complete, evaluation of the containing expression continues with
its original focus unchanged.</p> <ulist> <item> <p><termdef id="dt-context-item" term="context item">The <term>context item</term>
is the item currently being processed. An item is
either an atomic value or a node.</termdef><termdef id="dt-context-node" term="context node">When the context item is a
node, it can also be referred to as the <term>context
node</term>.</termdef> The context item is returned by an expression
consisting of a single dot (<code role="parse-test">.</code>). When an expression <code role="parse-test">E1/E2</code> or <code role="parse-test">E1[E2]</code> is evaluated, each item in the
sequence obtained by evaluating <code role="parse-test">E1</code>
becomes the context item in the inner focus for an evaluation of <code role="parse-test">E2</code>. </p> </item> <item> <p><termdef id="dt-context-position" term="context position">The <term>context
position</term> is the position of the context item within the
sequence of items currently being processed.</termdef> It changes whenever the context item
changes. When the focus is defined, the value of the context position is an integer greater than zero. The context
position is returned by the expression <code role="parse-test">fn:position()</code>. When an expression <code role="parse-test">E1/E2</code> or <code role="parse-test">E1[E2]</code> is evaluated, the context position in
the inner focus for an evaluation of <code role="parse-test">E2</code>
is the position of the context item in the sequence obtained by
evaluating <code role="parse-test">E1</code>. The position of the
first item in a sequence is always 1 (one). The context position is
always less than or equal to the context size.</p> </item> <item>
<p><termdef id="dt-context-size" term="context size">The <term>context
size</term> is the number of items in the sequence of items currently
being processed.</termdef> Its value is always an
integer greater than zero. The context size is returned by the
expression <code role="parse-test">fn:last()</code>. When an expression
<code role="parse-test">E1/E2</code> or <code role="parse-test">E1[E2]</code> is evaluated, the context size in the
inner focus for an evaluation of <code role="parse-test">E2</code> is
the number of items in the sequence obtained by evaluating <code role="parse-test">E1</code>. </p> </item>
			  
			 <item> 
				<p> <termdef id="dt-variable-values" term="variable values"><term>Variable values</term>. This is a set of
				(expanded QName, value) pairs. It contains the
				same <termref def="dt-expanded-qname">expanded QNames</termref> as the <termref def="dt-in-scope-variables">in-scope variables</termref> in the
				<termref def="dt-static-context">static context</termref> for the expression. The expanded QName is the name of the variable and the value is the dynamic value of the variable, which includes its <termref def="dt-dynamic-type">dynamic type</termref>.</termdef></p> 
				 
				 
			 </item><item><p><termdef term="function implementation" id="dt-function-implementation"><term>Function implementations</term>. Each function in <termref def="dt-function-signature">function signatures</termref> has a function implementation that enables the function to map instances of its parameter types into an instance of its result type. </termdef></p></item> 
			 <item> 
				<p> <termdef id="dt-date-time" term="current dateTime"><term>Current dateTime.</term> This information represents
				an <termref def="dt-implementation-dependent">implementation-dependent</termref> point in time during the processing of <phrase role="xpath">an expression</phrase>, and includes an explicit timezone. It can be retrieved by the  <code>fn:current-dateTime</code> function. If invoked multiple times during the execution of <phrase role="xpath">an expression</phrase>,
				this function always returns the same result.</termdef></p> 
			 </item><item><p><termdef id="dt-timezone" term="implicit timezone"><term>Implicit timezone.</term> This is the timezone to be used when a date,
time, or dateTime value that does not have a timezone is used in a
comparison or arithmetic operation. The implicit timezone is an  <termref def="dt-implementation-defined">implementation-defined</termref> value of type
<code>xs:dayTimeDuration</code>. See <bibref ref="XMLSchema"/> for the range of legal values
                         of a timezone.</termdef></p></item>
                         <item><p><termdef id="dt-available-docs" term="available documents"><term>Available
                         documents.</term> This is a mapping of
                         strings onto document nodes.  The string
                         represents the absolute URI of a
                         resource. The document node is the root of a tree that represents that resource using the <termref def="dt-datamodel">data model</termref>. The document node is returned by the <code>fn:doc</code> function when applied to that URI.</termdef> The set of available
                         documents is not limited to the set of <termref def="dt-known-docs">statically known
                         documents</termref>, and it may be
                         empty.</p><p>If there are one or more URIs in <termref def="dt-available-docs">available documents</termref> that map to a document
node <code>D</code>, then the document-uri property of <code>D</code> must either be absent, or must
be one of these URIs.</p><note><p>This means that given a document node <code>$N</code>, the result of
<code>fn:doc(fn:document-uri($N)) is $N</code> will always be True, unless
<code>fn:document-uri($N)</code> is an empty sequence.</p></note></item><item><p><termdef id="dt-available-collections" term="available collections"><term>Available
                         collections.</term> This is a mapping of
                         strings onto sequences of nodes. The string
                         represents the absolute URI of a
                         resource. The sequence of nodes represents
                         the result of the <code>fn:collection</code>
                         function when that URI is supplied as the
                         argument. </termdef> The set of available
                         collections is not limited to the set of <termref def="dt-known-collections">statically known
                         collections</termref>, and it may be empty.</p><p>For every document node <code>D</code> that is in the target of a mapping in <termref def="dt-available-collections">available collections</termref>, or that is the root of a tree containing such a node, the document-uri property of <code>D</code> must either be absent, or must be a
URI <code>U</code> such that <termref def="dt-available-docs">available documents</termref> contains a mapping from <code>U</code> to <code>D</code>."

</p><note><p>This means that for any document node <code>$N</code> retrieved using the
<code>fn:collection</code> function, either directly or by navigating to the root of a
node that was returned, the result of <code>fn:doc(fn:document-uri($N)) is $N</code>
will always be True, unless <code>fn:document-uri($N)</code> is an empty sequence. This
implies a requirement for the <code>fn:doc</code> and <code>fn:collection</code> functions to be
consistent in their effect. If the implementation uses catalogs or
user-supplied URI resolvers to dereference URIs supplied to the <code>fn:doc</code>
function, the implementation of the <code>fn:collection</code> function must take these
mechanisms into account. For example, an implementation might achieve this
by mapping the collection URI to a set of document URIs, which are then
resolved using the same catalog or URI resolver that is used by the <code>fn:doc</code> function.</p></note></item>
                         <item><p><termdef id="dt-default-collection" term="default collection"><term>Default collection.</term> This is the sequence of nodes that would result from calling the <code>fn:collection</code> function with no arguments.</termdef> The value of <term>default collection</term> may be initialized by the implementation.</p></item></ulist> </div3> </div2><div2 id="id-processing-model"><head>Processing
                         Model</head><p>XPath is defined in terms
                         of the <termref def="dt-datamodel">data
                         model</termref> and the <termref def="dt-expression-context">expression
                         context</termref>.</p> <graphic xmlns:xlink="http://www.w3.org/1999/xlink" source="ProcMod-XPath.gif" alt="Processing                          Model Overview" role="xpath" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/><p>Figure 1:
                         Processing Model Overview</p>

<p>Figure 1 provides a schematic overview of the processing steps that
are discussed in detail below. Some of these steps are completely
outside the domain of XPath; in Figure 1, these are depicted
outside the line that represents the boundaries of the language, an
area labeled <term>external processing</term>. The external processing
domain includes generation of an <termref def="dt-data-model-instance">XDM instance</termref> that represents the data to be queried (see <specref ref="id-data-model-generation"/>), schema import processing (see
<specref ref="id-schema-import-processing"/>) and serialization (see
<specref ref="id-serialization"/>). The area inside the boundaries of
the language is known as the <phrase role="xpath"><term>XPath processing domain</term></phrase>, which includes the static
analysis and dynamic evaluation phases (see <specref ref="id-expression-processing"/>).  Consistency constraints on the
<phrase role="xpath">XPath</phrase> processing domain are defined in <specref ref="id-consistency-constraints"/>.</p>


<div3 id="id-data-model-generation"><head>Data Model Generation</head>

<p>Before <phrase role="xpath">an expression</phrase> can be processed, its input data must be represented as an <termref def="dt-data-model-instance">XDM instance</termref>. This process occurs outside
the domain of XPath, which is why Figure 1 represents it in the
external processing domain. Here are some steps by which an XML
document might be converted to an <termref def="dt-data-model-instance">XDM instance</termref>:</p>

<olist><item><p>A document may be parsed using an XML parser that
generates an <term>XML Information Set</term> (see <bibref ref="XINFO"/>). The parsed document may then be validated against one
or more schemas. This process, which is described in <bibref ref="XMLSchema"/>, results in an abstract information structure called
the <term>Post-Schema Validation Infoset</term> (PSVI). If a document
has no associated schema, its Information Set is preserved. (See DM1
in Fig. 1.)</p> </item><item><p>The Information Set or PSVI may be
transformed into an <termref def="dt-data-model-instance">XDM instance</termref>
by a process described in <bibref ref="datamodel"/>. (See DM2 in
Fig. 1.)</p> </item></olist><p>The above steps provide an example of how an <termref def="dt-data-model-instance">XDM instance</termref> might be constructed. An XDM instance might
also be synthesized directly from a relational database, or
constructed in some other way (see DM3 in Fig. 1.) XPath is defined in terms
of the <termref def="dt-datamodel">data model</termref>,
but it does not place any constraints on how XDM instances are constructed.</p>

<p><termdef term="type annotation" id="dt-type-annotation">Each element node and attribute node in an <termref def="dt-data-model-instance">XDM instance</termref> has a <term>type annotation</term> (referred to in <bibref ref="datamodel"/> as its <code>type-name</code> property.) The type annotation of a node is a <termref def="dt-schema-type">schema type</termref> that describes the relationship between the <termref def="dt-string-value">string value</termref> of the node and its <termref def="dt-typed-value">typed value</termref>.</termdef>  If the <termref def="dt-data-model-instance">XDM instance</termref> was derived from a validated XML document as described in <xspecref spec="DM" ref="const-psvi"/>, the type annotations of the element and attribute nodes are derived from schema
validation. XPath does
not provide a way to directly access the type annotation of an element
or attribute node.</p><p>The value of an attribute is represented directly within the
attribute node. An attribute node whose type is unknown (such as might
occur in a schemaless document) is given the <termref def="dt-type-annotation">type annotation</termref>
<code>xs:untypedAtomic</code>.</p>

<p>The value of an element is represented by the children of the
element node, which may include text nodes and other element
nodes. The <termref def="dt-type-annotation">type annotation</termref> of an element node indicates how the values in
its child text nodes are to be interpreted. An element that has not been validated (such as might occur in a schemaless document) is annotated
with the schema type <code>xs:untyped</code>. An element that has been validated and found to be partially valid is annotated with the schema type <code>xs:anyType</code>. If an element node is annotated as <code>xs:untyped</code>, all its descendant element nodes are also annotated as <code>xs:untyped</code>. However, if an element node is annotated as <code>xs:anyType</code>, some of its descendant element nodes may have a more specific <termref def="dt-type-annotation">type annotation</termref>.</p>




</div3><div3 id="id-schema-import-processing"><head>Schema Import
Processing</head>

<p role="xpath">The <termref def="dt-issd">in-scope schema
definitions</termref> in the <termref def="dt-static-context">static
context</termref> are provided by the host language (see step SI1 in
Figure 1) and must satisfy the consistency constraints defined in
<specref ref="id-consistency-constraints"/>.

</p></div3><div3 id="id-expression-processing"><head>Expression
Processing</head><p>XPath defines two phases of processing called
the <termref def="dt-static-analysis">static analysis phase</termref>
and the <termref def="dt-dynamic-evaluation">dynamic evaluation
phase</termref> (see Fig. 1).  During the static analysis phase, <termref def="dt-static-error">static errors</termref>,  <termref def="dt-dynamic-error">dynamic errors</termref>, or <termref def="dt-type-error">type errors</termref> may be raised. During the dynamic evaluation phase, only <termref def="dt-dynamic-error">dynamic errors</termref> or <termref def="dt-type-error">type errors</termref> may be raised. These kinds of errors are defined in <specref ref="id-kinds-of-errors"/>.  </p><p>Within each phase, an implementation is free to use any
strategy or algorithm whose result conforms to the
specifications in this document.</p>

<div4 id="id-static-analysis"><head>Static Analysis Phase</head><p><termdef id="dt-static-analysis" term="static analysis phase">The
<term>static analysis phase</term> depends on the expression itself
and on the <termref def="dt-static-context">static context</termref>. The <term>static analysis phase</term> does
not depend on input data (other than schemas).</termdef></p>
<p>During the static analysis phase, the <phrase role="xpath">XPath expression</phrase> is parsed into an
internal representation called the <term>operation tree</term> (step
SQ1 in Figure 1).  A parse error is raised as a <termref def="dt-static-error">static error</termref> <errorref class="ST" code="0003"/>. The <termref def="dt-static-context">static context</termref> is initialized by the implementation (step SQ2).  The <termref def="dt-static-context">static context</termref> is used to resolve schema type names, function names, namespace prefixes, and variable names (step
SQ4). 
If a name of one of these kinds in the <term>operation tree</term> is
not found in the <termref def="dt-static-context">static context</termref>, a <termref def="dt-static-error">static error</termref> (<errorref class="ST" code="0008"/> or <errorref class="ST" code="0017"/>) is raised (however, see exceptions to this rule in <specref ref="id-element-test"/> and <specref ref="id-attribute-test"/>.)</p>

<p>The <term>operation tree</term> is then
<term>normalized</term> by making explicit the implicit operations
such as <termref def="dt-atomization">atomization</termref> and extraction of <termref def="dt-ebv">Effective Boolean Values</termref> (step SQ5). The
normalization process is described in <bibref ref="XQueryFormalSemantics"/>.</p>

<p> Each expression is then assigned a <termref def="dt-static-type">static type</termref> (step SQ6). 
<termdef id="dt-static-type" term="static type">The <term>static type</term> of an expression is a type such that, when the expression is evaluated, the resulting value will always conform to the static type.</termdef>
If the <termref def="dt-xpath-static-typing-feature" role="xpath">Static Typing Feature</termref> is supported, the <termref def="dt-static-type">static types</termref> of various expressions are inferred according to the rules described in <bibref ref="XQueryFormalSemantics"/>. If the <termref def="dt-xpath-static-typing-feature" role="xpath">Static Typing Feature</termref> is not supported, the static types that are assigned are <termref def="dt-implementation-dependent">implementation-dependent</termref>.</p>
<p> During the <termref def="dt-static-analysis">static analysis phase</termref>, if the <termref def="dt-xpath-static-typing-feature" role="xpath">Static Typing Feature</termref>
 is in effect and an operand of an expression is found to have
a <termref def="dt-static-type">static type</termref> that is not appropriate for that operand, a <termref def="dt-type-error">type error</termref> is raised <errorref class="TY" code="0004"/>.  If static type
checking raises no errors and assigns a <termref def="dt-static-type">static type</termref> T to an
expression, then execution of the expression on valid input data is
guaranteed either to produce a value of type T or to raise a <termref def="dt-dynamic-error">dynamic error</termref>.</p><p>The purpose of the  <termref def="dt-xpath-static-typing-feature" role="xpath">Static Typing Feature</termref> is to provide early detection of <termref def="dt-type-error">type errors</termref> and to infer type information that may be useful in optimizing the evaluation of an expression.</p></div4><div4 id="id-dynamic-evaluation"><head>Dynamic Evaluation Phase</head><p><termdef id="dt-dynamic-evaluation" term="dynamic evaluation phase">The <term>dynamic evaluation phase</term> is the phase during which the value of an expression is computed.</termdef> It occurs after completion of the <termref def="dt-static-analysis">static analysis phase</termref>.</p><p>The dynamic evaluation phase can occur only if no errors were detected during the <termref def="dt-static-analysis">static analysis phase</termref>. If the <termref def="dt-xpath-static-typing-feature" role="xpath">Static Typing Feature</termref> is in effect, all <termref def="dt-type-error">type errors</termref> are detected during static analysis and serve to inhibit the dynamic evaluation phase.</p><p>The dynamic evaluation phase depends on the <term>operation
tree</term> of the expression being evaluated (step DQ1), on the input
data (step DQ4), and on the <termref def="dt-dynamic-context">dynamic context</termref> (step DQ5), which in turn draws information from  the external environment (step DQ3) and the <termref def="dt-static-context">static context</termref> (step DQ2). The dynamic evaluation phase may create new data-model values (step DQ4) and it may extend the <termref def="dt-dynamic-context">dynamic context</termref> (step DQ5)—for example, by binding values to variables.</p>

<p><termdef term="dynamic type" id="dt-dynamic-type">A <term>dynamic type</term> is associated with each value as it is computed. The dynamic type of a value may be more specific than the <termref def="dt-static-type">static type</termref> of the expression that computed it (for example, the  static type of an expression might be <code>xs:integer*</code>, denoting a sequence of zero or more integers, but at evaluation time its value may have the dynamic type <code>xs:integer</code>, denoting exactly one integer.)</termdef></p><p> If an operand of an expression is found
to have a <termref def="dt-dynamic-type">dynamic type</termref> that is not appropriate for that operand, a
<termref def="dt-type-error">type error</termref> is
raised <errorref class="TY" code="0004"/>.</p><p>Even though static typing can catch many <termref def="dt-type-error">type errors</termref> before an expression is executed, it is possible for an expression to raise an error during evaluation that was not detected by static  analysis. For example, an expression may contain a cast of a string into an integer, which is statically valid. However, if the actual value of the string at run time cannot be cast into an integer, a <termref def="dt-dynamic-error">dynamic error</termref> will result. Similarly, an expression may apply an arithmetic operator to a value whose <termref def="dt-static-type">static type</termref> is <code>xs:untypedAtomic</code>. This is not a <termref def="dt-static-error">static error</termref>, but at run time, if the value cannot be successfully cast to a <termref def="dt-numeric">numeric</termref> type, a <termref def="dt-dynamic-error">dynamic error</termref> will be raised.</p><p>When the <termref def="dt-xpath-static-typing-feature" role="xpath">Static Typing Feature</termref> is in effect, it is also possible for static analysis of an expression to raise a <termref def="dt-type-error">type error</termref>, even though execution of the expression on certain inputs would be successful. For example, an expression might contain a function that requires an element as its parameter, and the static analysis phase might infer the <termref def="dt-static-type">static type</termref> of the function parameter to be an optional element. This case is treated as a <termref def="dt-type-error">type error</termref> and inhibits evaluation, even though the function call would have been successful for input data in which the optional element is present.</p></div4></div3><div3 id="id-serialization"><head>Serialization</head><p><termdef id="dt-serialization" term="serialization"><term>Serialization</term> is the process of converting an <termref def="dt-data-model-instance">XDM instance</termref> into a sequence of octets (step DM4 in Figure 1.) </termdef> The general
framework for serialization is described in <bibref ref="serialization"/>.</p><p role="xpath">The host language may provide a serialization option.</p></div3><div3 id="id-consistency-constraints">

<head>Consistency Constraints</head><p>In order for XPath to
be well defined, the input <termref def="dt-data-model-instance">XDM instance</termref>, the <termref def="dt-static-context">static context</termref>, and the <termref def="dt-dynamic-context">dynamic context</termref> must be mutually
consistent. The consistency constraints listed below are prerequisites
for correct functioning of an XPath implementation. Enforcement
of these consistency constraints is beyond the scope of this
specification. This specification does not
define the result of   <phrase role="xpath">an expression</phrase> under any condition in which one
or more of these constraints is not satisfied.</p><p>Some of the consistency constraints use the term
<term>data model schema</term>. <termdef id="dt-data-model-schema" term="data model schema">For a given node in an <termref def="dt-data-model-instance">XDM instance</termref>, the
<term>data model schema</term> is defined as the schema from which the
<termref def="dt-type-annotation">type annotation</termref> of that node was derived.</termdef> For a node that was constructed by some
process other than schema validation, the <term>data model schema</term>
consists simply of the schema type definition that is represented by the <termref def="dt-type-annotation">type annotation</termref> of the node.</p>
<ulist>



<item><p>For every  node that has a type annotation, if that type annotation is found in the <termref def="dt-issd">in-scope schema definitions</termref> (ISSD), then its definition in the ISSD must be equivalent to its definition in the <termref def="dt-data-model-schema">data model schema</termref>. Furthermore, all types that are derived by extension from the given type in the <termref def="dt-data-model-schema">data model schema</termref> must also be known by equivalent definitions in the ISSD.</p></item><item><p>For every element name <emph>EN</emph> that is found both in an <termref def="dt-data-model-instance">XDM instance</termref> and in the <termref def="dt-issd">in-scope schema definitions</termref> (ISSD), all elements that are known in the <termref def="dt-data-model-schema">data model schema</termref> to be in the <termref def="dt-substitution-group">substitution group</termref> headed by <emph>EN</emph> must also be known in the ISSD to be in the <termref def="dt-substitution-group">substitution group</termref> headed by <emph>EN</emph>.</p></item><item><p>Every element name, attribute name, or schema type name referenced in <termref def="dt-in-scope-variables">in-scope variables</termref> or <termref def="dt-function-signature">function signatures</termref> must be in the <termref def="dt-issd">in-scope schema definitions</termref>, unless it is an element name referenced as part of an <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-ElementTest" xlink:type="simple">ElementTest</nt> or an attribute name referenced as part of an <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-AttributeTest" xlink:type="simple">AttributeTest</nt>.</p></item><item><p>Any reference to a global element, attribute, or type name in
the <termref def="dt-issd">in-scope schema definitions</termref> must have a corresponding element, attribute or type
definition in the <termref def="dt-issd">in-scope schema definitions</termref>.</p></item>


<item><p> For each mapping of a string to a
document node in <termref def="dt-available-docs">available
documents</termref>, if there exists a mapping of the same string to a document type in <termref def="dt-known-docs">statically known documents</termref>, the document node must match the document type, using the matching rules in <specref ref="id-sequencetype-matching"/>.</p></item>
<item><p> For each mapping of a string to a sequence of nodes in
<termref def="dt-available-collections">available
collections</termref>, if there exists a mapping of the same string to
a type in <termref def="dt-known-collections">statically known collections</termref>, the sequence of nodes must match the type, using the matching rules in  <specref ref="id-sequencetype-matching"/>.</p></item><item><p>The sequence of nodes in the <termref def="dt-default-collection">default collection</termref> must match the <termref def="dt-known-default-collection">statically known default collection type</termref>, using the matching rules in  <specref ref="id-sequencetype-matching"/>.</p></item><item><p>The value of the <termref def="dt-context-item">context item</termref> must match the <termref def="dt-context-item-static-type">context item static type</termref>, using the
matching rules in <specref ref="id-sequencetype-matching"/>.</p></item>
<item><p>For each (variable, type) pair in <termref def="dt-in-scope-variables">in-scope variables</termref> and the corresponding (variable, value) pair in <termref def="dt-variable-values">variable values</termref> such that the variable names are equal, the value must match the type, using the matching rules in  <specref ref="id-sequencetype-matching"/>.</p></item><item><p>In the <termref def="dt-static-namespaces">statically known namespaces</termref>, the prefix <code>xml</code> must not be bound to any namespace URI other than <code>http://www.w3.org/XML/1998/namespace</code>, and no prefix other than <code>xml</code> may be bound to this namespace URI.</p></item>
</ulist>
</div3></div2>

<div2 id="errors">
<head>Error Handling</head>

<div3 id="id-kinds-of-errors"><head>Kinds of Errors</head><p>
As described in <specref ref="id-expression-processing"/>, XPath
defines a <termref def="dt-static-analysis">static analysis phase</termref>, which does not depend on input
data, and a <termref def="dt-dynamic-evaluation">dynamic evaluation
phase</termref>, which does depend on input
data.  Errors may be raised during each phase.</p>

<p><termdef id="dt-static-error" term="static error">
A <term>static error</term> is an 
error that
must be detected during the static analysis phase.
A syntax error is an example of a <termref def="dt-static-error">static error</termref>.</termdef></p>
<p>
<termdef id="dt-dynamic-error" term="dynamic error">A <term>dynamic
error</term> is an error that
must be detected during the dynamic evaluation phase and may be detected
during the static analysis phase.
Numeric overflow is an example of a dynamic error. 
</termdef>
</p>
<p>
<termdef id="dt-type-error" term="type error">A <term>type
error</term> may be raised during the static analysis phase or the dynamic evaluation phase.
During the static analysis phase, a <termref def="dt-type-error">type error</termref> occurs
when the <termref def="dt-static-type">static type</termref> of an expression does not match the expected type
of the context in which the expression occurs.
During the dynamic evaluation phase, a <termref def="dt-type-error">type error</termref> occurs 
when the <termref def="dt-dynamic-type">dynamic type</termref> of a value does not match the expected type of 
the context in which the value occurs.</termdef></p>

<p>The outcome of the <termref def="dt-static-analysis">static analysis
phase</termref> is either success or one or more <termref def="dt-type-error">type errors</termref>, <termref def="dt-static-error">static errors</termref>, or statically-detected <termref def="dt-dynamic-error">dynamic errors</termref>. The result of the <termref def="dt-dynamic-evaluation">dynamic evaluation
phase</termref> is either a result value, a <termref def="dt-type-error">type
error</termref>, or a <termref def="dt-dynamic-error">dynamic error</termref>.</p><p>If more than one error is present, or if an error condition comes within the
scope of more than one error defined in this specification, then any non-empty
subset of these errors may be reported.</p>

<p> During the <termref def="dt-static-analysis">static
analysis phase</termref>, if the <termref def="dt-xpath-static-typing-feature" role="xpath">Static Typing Feature</termref> is in effect and the <termref def="dt-static-type">static type</termref> assigned to an expression other than <code>()</code> or <code>data(())</code> is <code>empty-sequence()</code>, a <termref def="dt-static-error">static error</termref> is raised <errorref class="ST" code="0005"/>. This catches cases in which a query refers to an element or attribute that is not present in the <termref def="dt-issd">in-scope schema definitions</termref>, possibly because of a spelling error.</p><p>Independently of whether the <termref def="dt-xpath-static-typing-feature" role="xpath">Static Typing Feature</termref> is in effect, if an implementation can determine during the 
<termref def="dt-static-analysis">static
analysis phase</termref> that an expression, if evaluated, would necessarily 
raise a <termref def="dt-type-error">type
error</termref> or a <termref def="dt-dynamic-error">dynamic error</termref>, the implementation may (but is not required to) report that 
error during the <termref def="dt-static-analysis">static
analysis phase</termref>. However, the
<code>fn:error()</code> function must not be evaluated during the
<termref def="dt-static-analysis">static analysis
phase</termref>.</p><p><termdef id="dt-warning" term="warning">In addition to <termref def="dt-static-error">static errors</termref>, <termref def="dt-dynamic-error">dynamic errors</termref>, and <termref def="dt-type-error">type
errors</termref>, an XPath
implementation may raise <term>warnings</term>, either during the <termref def="dt-static-analysis">static analysis
phase</termref> or the
<termref def="dt-dynamic-evaluation">dynamic evaluation
phase</termref>. The circumstances in which warnings are raised, and
the ways in which warnings are handled, are <termref def="dt-implementation-defined">implementation-defined</termref>.</termdef></p><p>In addition to the errors defined in this
specification, an implementation may raise a <termref def="dt-dynamic-error">dynamic error</termref> for a reason beyond the scope of this specification. For
example, limitations may exist on the maximum
numbers or sizes of various objects. Any such  limitations, and the
consequences of exceeding them, are <termref def="dt-implementation-dependent">implementation-dependent</termref>.</p></div3><div3 id="id-identifying-errors"><head>Identifying and Reporting Errors</head><p>The errors defined in this specification are identified by QNames that have the form <code role="xpath">err:XPYYnnnn</code>, where:</p><ulist><item><p><code>err</code> denotes the namespace for XPath and XQuery errors, <code>http://www.w3.org/2005/xqt-errors</code>. This binding of the namespace prefix <code>err</code> is used for convenience in this document, and is not normative.</p></item><item role="xpath"><p><code>XP</code> identifies the error as an XPath error.</p></item><item><p><code>YY</code> denotes the error category, using the following encoding:</p><ulist><item><p><code>ST</code> denotes a static error.</p></item><item><p><code>DY</code> denotes a dynamic error.</p></item><item><p><code>TY</code> denotes a type error.</p></item></ulist></item><item><p><code>nnnn</code> is a unique numeric code.</p></item></ulist><note><p>The namespace URI for  XPath and XQuery errors is not expected to 
change from one version of XPath to another. However, the contents of this 
namespace may be extended to include additional error definitions.</p></note><p>The method by which an XPath processor reports error information to the external environment is <termref def="dt-implementation-defined">implementation-defined</termref>.</p><p>An error can be represented by a URI reference that is derived from the error QName as follows: an error with namespace URI <emph><code>NS</code></emph> and local part <emph><code>LP</code></emph> can be represented as the URI reference <emph><code>NS</code></emph><code>#</code><emph><code>LP</code></emph>. For example, an error whose QName is <code>err:XPST0017</code> could be represented as <code>http://www.w3.org/2005/xqt-errors#XPST0017</code>.</p><note><p>Along with a code identifying an error, implementations may wish to return additional information, such 
as the location of the error or the processing phase in which it was detected. If an implementation chooses to do so, then the mechanism that 
it uses to return this information is <termref def="dt-implementation-defined">implementation-defined</termref>.</p></note></div3>

<div3 id="id-handling-dynamic"><head>Handling Dynamic Errors</head>
<p>Except as noted in this document, if any operand of an expression
raises a <termref def="dt-dynamic-error">dynamic error</termref>, the expression also raises a <termref def="dt-dynamic-error">dynamic error</termref>.
If an expression can validly return a value or raise a dynamic
error, the implementation may choose to return the value or raise
the dynamic error.  For example, the logical expression 
<code>expr1 and expr2</code> may return the value <code>false</code> 
if either operand returns <code>false</code>,
or may raise a dynamic error if either operand raises a dynamic
error.</p><p> If more than one operand of an expression raises 
an error, the
implementation may choose which error is raised by the expression.
For example, in this expression:

</p><eg role="parse-test" xml:space="preserve">($x div $y) + xs:decimal($z)</eg><p>

both the sub-expressions <code>($x div $y)</code> and <code>xs:decimal($z)</code> may 
raise an error.  The
implementation may choose which error is raised by the "<code>+</code>"
expression.  Once one operand raises an error, the implementation is
not required, but is permitted, to evaluate any other operands.</p>

<p><termdef id="dt-error-value" term="error value">In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called <term>error values</term>.</termdef> An implementation 
may provide a mechanism whereby an
application-defined error handler can process error values and
produce diagnostic messages.</p>

<p>A dynamic error may be raised by a <termref def="dt-built-in-function">built-in 
function</termref> or operator.  For example,
the <code>div</code> operator raises an error if its operands are <code>xs:decimal</code> values and its second operand
is equal to zero. Errors raised by built-in functions and operators are defined in <bibref ref="FunctionsAndOperators"/>.</p>

<p>A dynamic error can also be raised explicitly by calling the
<code>fn:error</code> function, which only raises an error and never
returns a value.  This function is defined in <bibref ref="FunctionsAndOperators"/>. For example, the following
function call raises a dynamic
error, providing a QName that identifies the error, a descriptive string, and a diagnostic value (assuming that the prefix <code>app</code> is bound to a namespace containing application-defined error codes):</p>

<eg role="parse-test" xml:space="preserve">fn:error(xs:QName("app:err057"), "Unexpected value", fn:string($v))</eg>

</div3><div3 id="id-errors-and-opt"><head>Errors and
      Optimization</head><p>Because different implementations may
      choose to evaluate or optimize an expression in different ways,
      certain aspects of the detection and reporting of <termref def="dt-dynamic-error">dynamic errors</termref> are <termref def="dt-implementation-dependent">implementation-dependent</termref>, as described in this section.</p><p>An implementation is always free to evaluate the operands of an operator in any order.</p><p>In some cases,  a processor can determine the result of an expression without accessing all the data that would be implied by the formal expression semantics. For example, the formal description of <termref def="dt-filter-expression">filter expressions</termref> suggests that <code>$s[1]</code> should be evaluated by examining all the items in sequence <code>$s</code>, and selecting all those that satisfy the predicate <code>position()=1</code>. In practice, many implementations will recognize that they can evaluate this expression by taking the first item in the sequence and then exiting. If <code>$s</code> is defined by an expression such as <code>//book[author eq 'Berners-Lee']</code>, then this strategy may avoid a complete scan of a large document and may therefore greatly improve performance. However, a consequence of this strategy is that a dynamic error or type error that would be detected if the expression semantics were followed literally might not be detected at all if the evaluation exits early. In this example, such an error might occur if there is a <code>book</code> element in the input data with more than one <code>author</code> subelement.</p><p>The extent to which a processor may optimize its access to data, at the cost of not detecting errors, is defined by the following rules.</p><p>Consider an expression <emph>Q</emph> that has an operand (sub-expression) <emph>E</emph>. In general the value of <emph>E</emph> is a sequence. At an intermediate stage during evaluation of the sequence, some of its items will be known and others will be unknown. If, at such an intermediate stage of evaluation, a processor is able to establish that there are only two possible outcomes of evaluating <emph>Q</emph>, namely the value <emph>V</emph> or an error, then the processor may deliver the result <emph>V</emph> without evaluating further items in the operand <emph>E</emph>. For this purpose, two values are considered to represent the same outcome if their items are pairwise the same, where nodes are the same if they have the same identity, and values are the same if they are equal and have exactly the same type.</p><p>There is an exception to this rule: If a processor evaluates an operand <emph>E</emph> (wholly or in part), then it  is required to establish that the actual value of the operand <emph>E</emph> does not violate any constraints on its cardinality. For example, the expression <code>$e eq 0</code> results in a type error if the value of <code>$e</code> contains two or more items. A processor is not allowed to decide, after evaluating the first item in the value of <code>$e</code> and finding it equal to zero, that the only possible outcomes are the value <code>true</code> or a type error caused by the cardinality violation. It must establish that the value of <code>$e</code> contains no more than one item.</p>
<p>These rules apply to all the operands of an expression considered in combination: thus if an expression has two operands <emph>E1</emph> and <emph>E2</emph>, it may be evaluated using any samples of the respective sequences that satisfy the above rules.</p><p>The rules cascade: if <emph>A</emph> is an operand of <emph>B</emph> and <emph>B</emph> is an operand of <emph>C</emph>, then the processor needs to evaluate only a sufficient sample of <emph>B</emph> to determine the value of <emph>C</emph>, and needs to evaluate only a sufficient sample of <emph>A</emph> to determine this sample of <emph>B</emph>.</p><p>The effect of these rules is that the processor is free to stop examining further items in a sequence as soon as it can establish that further items would not affect the result except possibly by causing an error. For example, the processor may return <code>true</code> as the result of the expression <code>S1 = S2</code> as soon as it finds a pair of equal values from the two sequences.</p><p>Another consequence of these rules is that where none of the items in a sequence contributes to the result of an expression, the processor is not obliged to evaluate any part of the sequence. Again, however, the processor cannot dispense with a required cardinality check: if an empty sequence is not permitted in the relevant context, then the processor must ensure that the operand is not an empty sequence.</p><p>Examples:</p>

<ulist><item><p>If an implementation can find (for example, by using an index) that at 
least one item returned by <code>$expr1</code> in the following example has the value <code>47</code>, it is allowed to 
return <code>true</code> as the result of the <code>some</code> expression, without searching for 
another item returned by <code>$expr1</code> that would raise an error if it were evaluated.
</p><eg role="parse-test" xml:space="preserve">some $x in $expr1 satisfies $x = 47</eg></item><item><p>In the following example, if an implementation can find (for example, by using an index) the 
<code>product</code> element-nodes that have an <code>id</code> child with the value <code>47</code>, it is allowed to return these nodes as the 
result of the <termref def="dt-path-expression">path expression</termref>, without searching for another <code>product</code> node that 
would raise an error because it has an <code>id</code> child whose value is not an integer.</p><eg role="parse-test" xml:space="preserve">//product[id = 47]</eg></item></ulist><p>For a variety of reasons, including optimization,  implementations are free to rewrite expressions into equivalent expressions.  Other than the raising or not raising of errors, the result of evaluating an equivalent expression must be the same as the result of evaluating the original expression. Expression rewrite is illustrated by the following examples.</p>

<ulist><item><p>Consider the expression <code>//part[color eq "Red"]</code>. An implementation might 
choose to rewrite this expression as <code>//part[color = "Red"][color eq 
"Red"]</code>. The implementation might then process the expression as follows: 
First process the "<code>=</code>" predicate by probing an index on parts by color to 
quickly find all the parts that have a Red color; then process the "<code>eq</code>" 
predicate by checking each of these parts to make sure it has only a 
single color. The result would be as follows: 
<ulist><item><p>Parts that have exactly one color that is Red are returned.</p></item><item><p>If some part has color Red together with some other color, an error is 
raised.</p></item><item><p>The existence of some part that has no color Red but has multiple non-Red 
colors does not trigger an error.</p></item></ulist></p></item><item><p>The expression in the following example cannot raise a casting error if it is evaluated
exactly as written (i.e., left to right). Since neither predicate depends on the context position, an implementation might choose to reorder the predicates to achieve better
performance (for example, by taking advantage of an index). This
reordering could cause the expression to raise an
error.</p><eg role="parse-test" xml:space="preserve">$N[@x castable as xs:date][xs:date(@x) gt xs:date("2000-01-01")]</eg><p>To avoid unexpected errors caused by expression rewrite,
tests that are designed to prevent dynamic errors should be expressed
using conditional  expressions. Conditional  expressions raise only dynamic errors that occur in the branch that is actually selected. Thus, unlike the previous example, the following example cannot raise a dynamic error if <code>@x</code> is not castable into an <code>xs:date</code>:</p><eg role="parse-test" xml:space="preserve">$N[if (@x castable as xs:date)
   then xs:date(@x) gt xs:date("2000-01-01")
   else false()]</eg></item></ulist>






</div3></div2><div2 id="id-important-concepts"><head>Concepts</head>

<p>This section explains some concepts that are important to the processing of XPath expressions.</p>

<div3 id="id-document-order"><head>Document Order</head>

        <p>An ordering called <term>document order</term> is defined among all the nodes accessible during processing of a given <phrase role="xpath">expression</phrase>, which may consist of one or more <term>trees</term> (documents or fragments). Document order is defined in <bibref ref="datamodel"/>, and its definition is repeated here for convenience. <termdef term="reverse document order" id="dt-reverse-document-order">The node ordering that is the reverse of document order is called <term>reverse document order</term>.</termdef></p>

<p>Document order is a total ordering, although the relative order of some nodes is <termref def="dt-implementation-dependent">implementation-dependent</termref>.  <termdef term="document order" id="dt-document-order">Informally, <term>document order</term> is the order in
which nodes appear in the XML serialization of a document.</termdef>  <termdef term="stable" id="stable">Document order is <term>stable</term>, which means that the relative order of two nodes will not change during the processing of a given <phrase role="xpath">expression</phrase>, even if this order is <termref def="dt-implementation-dependent">implementation-dependent</termref>.</termdef></p>

<p>Within a tree, document order satisfies the following constraints:</p>

<olist>
<item><p>The root node is the first node.</p></item>

<item><p>Every node occurs before all of its children and descendants.</p></item>

<item role="xpath"><p>Namespace nodes immediately follow the element node with
which they are associated. The relative order of namespace nodes is
stable but <termref def="dt-implementation-dependent">implementation-dependent</termref>.</p></item>

<item><p>Attribute nodes immediately follow the <phrase role="xpath">namespace nodes of the
</phrase> element node with which they are associated. The relative order of
attribute nodes is stable but <termref def="dt-implementation-dependent">implementation-dependent</termref>.</p></item>

<item><p>The relative order of siblings is the order in which they occur
in the <code>children</code> property of their parent node.</p></item><item><p>Children and descendants occur before following siblings.</p></item>
</olist>

<p>The relative order of nodes in distinct trees is stable but
<termref def="dt-implementation-dependent">implementation-dependent</termref>,
subject to the following constraint: If any node in a given tree T1 is before
any node in a different tree T2, then all nodes in tree T1 are before all nodes in
tree T2.</p>

        </div3>

	 <div3 id="id-atomization"><head>Atomization</head><p>The semantics of some
XPath operators depend on a process called <termref def="dt-atomization">atomization</termref>. Atomization is
applied to a value when the value is used in a context in which a
sequence of atomic values is required. The result of atomization is
either a sequence of atomic values or a <termref def="dt-type-error">type error</termref>  [err:FOTY0012].  <termdef id="dt-atomization" term="atomization"><term>Atomization</term> of a sequence
is defined as the result of invoking the <code>fn:data</code> function
on the sequence, as defined in <bibref ref="FunctionsAndOperators"/>.</termdef></p> <p> The semantics of
<code>fn:data</code> are repeated here for convenience. The result of
<code>fn:data</code> is the sequence of atomic values produced by
applying the following rules to each item in the input
sequence:</p><ulist> <item><p>If the item is an atomic value, it is
returned.</p></item><item><p>If the item is a node, 
its <termref def="dt-typed-value">typed value</termref> is returned (err:FOTY0012 is raised if the node has no typed value.)</p></item>
			  
			 </ulist><p>Atomization is  used in
processing the following types of expressions: </p><ulist><item><p>Arithmetic expressions</p></item><item><p>Comparison expressions</p></item><item><p>Function calls and returns</p></item><item><p>Cast expressions</p></item></ulist></div3><div3 id="id-ebv"><head>Effective Boolean Value</head><p>Under certain circumstances (listed below), it is necessary to find
the <termref def="dt-ebv">effective boolean value</termref> of a
value. <termdef id="dt-ebv" term="effective boolean value">The
<term>effective boolean value</term> of a value is defined as the result
of applying the <code>fn:boolean</code> function to the value, as
defined in <bibref ref="FunctionsAndOperators"/>.</termdef></p>

<p> The dynamic semantics of <code>fn:boolean</code> are repeated here for convenience:</p><olist><item><p>If its operand is an empty sequence, <code>fn:boolean</code> returns <code>false</code>.</p></item><item><p>If its operand is a sequence whose first item is a node, <code>fn:boolean</code> returns <code>true</code>.</p></item><item><p>If its operand is a <termref def="dt-singleton">singleton</termref> value of type <code>xs:boolean</code> or derived from <code>xs:boolean</code>, <code>fn:boolean</code> returns the value of its operand unchanged.</p></item><item><p>If its operand is a <termref def="dt-singleton">singleton</termref> value of type <code>xs:string</code>, <code>xs:anyURI</code>, <code>xs:untypedAtomic</code>, or a type derived from one of these, <code>fn:boolean</code> returns <code>false</code> if the operand value has zero length; otherwise it returns <code>true</code>.</p></item><item><p>If its operand is a <termref def="dt-singleton">singleton</termref> value of any <termref def="dt-numeric">numeric</termref> type or derived from a numeric type, <code>fn:boolean</code> returns <code>false</code> if the operand value is <code>NaN</code> or is numerically equal to zero; otherwise it returns <code>true</code>.</p></item><item><p>



In all other cases, <code>fn:boolean</code> raises a type error [err:FORG0006].
</p></item></olist><note><p>The static semantics of  <code>fn:boolean</code> are defined in <xspecref spec="FS" ref="sec_fn_boolean"/>.</p></note><p>The <termref def="dt-ebv">effective boolean value</termref> of a sequence is computed implicitly during  processing of the following types of expressions: </p><ulist><item><p>Logical expressions (<code>and</code>, <code>or</code>)</p></item><item><p>The <code>fn:not</code> function</p></item><item><p>Certain types of <termref def="dt-predicate">predicates</termref>, such as <code>a[b]</code></p></item><item><p>Conditional expressions (<code>if</code>)</p></item><item><p>Quantified expressions (<code>some</code>, <code>every</code>)</p></item><item role="xpath"><p>General comparisons, in <termref def="dt-xpath-compat-mode">XPath 1.0
		compatibility mode</termref>.</p></item></ulist><note><p>The definition of <termref def="dt-ebv">effective boolean value</termref> is <emph>not</emph> used when casting a value to the type <code>xs:boolean</code>, for example in a <code>cast</code> expression or when passing a value to a function whose expected parameter is of type <code>xs:boolean</code>.</p></note></div3><div3 id="id-input-sources"><head>Input Sources</head><p>XPath has a set of functions that provide access to
    input data. These functions are of particular importance because they provide a way in which an expression can reference a document or a collection of documents. The  input functions are described informally here; they are defined in <bibref ref="FunctionsAndOperators"/>.</p>

    <p>An expression can access input data either by calling one
    of the input functions or by referencing some part of the
    <termref def="dt-dynamic-context">dynamic context</termref> that is initialized by the external
    environment, such as a <termref def="dt-variable-values">variable</termref> or 
    <termref def="dt-context-item">context item</termref>.</p>

    <p>The input functions supported by XPath are as follows:</p>

    <ulist><item><p>The <code>fn:doc</code> function takes a string containing a URI. If that URI is associated with a document in <termref def="dt-available-docs">available documents</termref>, <code>fn:doc</code> returns a document node whose content is the <termref def="dt-datamodel">data model</termref> representation of the given document; otherwise it raises a <termref def="dt-dynamic-error">dynamic error</termref> (see <bibref ref="FunctionsAndOperators"/> for details).</p></item><item><p>The <code>fn:collection</code> function with one argument takes a string containing a URI. If that URI is associated with a collection in <termref def="dt-available-collections">available collections</termref>, <code>fn:collection</code> returns the data model representation of that collection; otherwise it raises a <termref def="dt-dynamic-error">dynamic error</termref> (see <bibref ref="FunctionsAndOperators"/> for details).  A collection may be any sequence of nodes. For example, the expression
    <code>fn:collection("http://example.org")//customer</code>
    identifies all the <code>customer</code> elements that are
    descendants of nodes found in the collection whose URI is
    <code>http://example.org</code>.</p></item><item><p>The <code>fn:collection</code> function with zero arguments returns the <termref def="dt-default-collection">default collection</termref>, an <termref def="dt-implementation-dependent">implementation-dependent</termref> sequence of nodes.</p></item></ulist>

    

    </div3></div2>
	 <div2 id="id-types"> 
		<head>Types</head> 
		<p> The type system of  XPath is based on
		<bibref ref="XMLSchema"/>, and is formally defined in
		<bibref ref="XQueryFormalSemantics"/>.</p><p><termdef id="dt-sequence-type" term="sequence type">A <term>sequence type</term> is a type that can be expressed using the <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-SequenceType" xlink:type="simple">SequenceType</nt>
syntax. Sequence types are used whenever it is necessary to refer to a type in an XPath expression. The term <term>sequence type</term> suggests that this syntax is used to describe the type of an XPath value, which is always a sequence.</termdef></p><p><termdef id="dt-schema-type" term="schema type">A <term>schema type</term> is a type that is (or could be) defined using the facilities of <bibref ref="XMLSchema"/> (including the built-in types of <bibref ref="XMLSchema"/>).</termdef> A schema type  can be used as a type annotation on an
element or attribute node (unless it is a non-instantiable type such as <code>xs:NOTATION</code> or <code>xs:anyAtomicType</code>, in which case its derived
types can be so used). Every schema type is either a <term>complex type</term> or a
<term>simple type</term>; simple types are further subdivided into <term>list types</term>, <term>union
types</term>, and <term>atomic types</term> (see <bibref ref="XMLSchema"/> for definitions and explanations of these terms.)</p><p>Atomic types represent the intersection between the categories of <termref def="dt-sequence-type">sequence type</termref> and <termref def="dt-schema-type">schema type</termref>. An
atomic type, such as <code>xs:integer</code> or <code>my:hatsize</code>, is both a <termref def="dt-sequence-type">sequence type</termref> and a
<termref def="dt-schema-type">schema type</termref>.</p> 
		 
	
		<div3 id="id-predefined-types"><head>Predefined Schema Types</head>


                 <p role="xpath">The <termref def="dt-is-types">in-scope schema types</termref>
                 in the <termref def="dt-static-context">static
                 context</termref> are initialized with a set of
                 predefined schema types that is determined by the host
                 language. This set may include some or all of the
                 schema types in the
                 namespace
                 <code>http://www.w3.org/2001/XMLSchema</code>,
                 represented in this document by the namespace prefix
                 <code>xs</code>. The schema types in this namespace are defined in <bibref ref="XMLSchema"/>
                 and augmented by additional types defined in <bibref ref="datamodel"/>. The schema types defined in  <bibref ref="datamodel"/> are summarized below.</p>


                   

<olist><item><p><termdef term="xs:untyped" id="dt-untyped"><code>xs:untyped</code> is  used as the <termref def="dt-type-annotation">type annotation</termref> of an element node that has not been validated, or has been validated in <code>skip</code> mode.</termdef> No predefined schema types are derived from <code>xs:untyped</code>.</p></item><item><p><termdef id="dt-untypedAtomic" term="xs:untypedAtomic"><code>xs:untypedAtomic</code>
is an atomic type that is used to denote untyped atomic data, such as text that has not been assigned a more specific type.</termdef> An attribute that has been validated in <code>skip</code> mode is represented in the <termref def="dt-datamodel">data model</termref> by an attribute node with the <termref def="dt-type-annotation">type annotation</termref> <code>xs:untypedAtomic</code>. No predefined schema types are derived from <code>xs:untypedAtomic</code>.</p></item><item><p><termdef term="xs:dayTimeDuration" id="dt-dayTimeDuration"><code>xs:dayTimeDuration</code> is derived by restriction from <code>xs:duration</code>. The  lexical representation of <code>xs:dayTimeDuration</code>
is restricted to contain only day, hour, minute, and second
components.</termdef></p></item><item><p><termdef term="xs:yearMonthDuration" id="dt-yearMonthDuration"><code>xs:yearMonthDuration</code> is derived by restriction from <code>xs:duration</code>. The lexical representation of <code>xs:yearMonthDuration</code> is
restricted to contain only year and month
components.</termdef></p></item><item><p><termdef term="xs:anyAtomicType" id="dt-anyAtomicType"><code>xs:anyAtomicType</code> is an atomic type that includes all atomic values (and no values that
are not atomic). Its base type is
<code>xs:anySimpleType</code> from which all simple types, including atomic,
list, and union types, are derived. All primitive atomic types, such as
<code>xs:integer</code>, <code>xs:string</code>, and <code>xs:untypedAtomic</code>, have <code>xs:anyAtomicType</code> as their base type.</termdef></p><note><p><code>xs:anyAtomicType</code>  will not appear as the type of an actual value in an <termref def="dt-data-model-instance">XDM instance</termref>.</p></note></item></olist><p>The relationships among the schema types in the <code>xs</code> namespace are illustrated in Figure 2. A more complete description of the XPath type hierarchy can be found in <bibref ref="FunctionsAndOperators"/>.</p><graphic xmlns:xlink="http://www.w3.org/1999/xlink" source="types.jpg" alt="Type Hierarchy Diagram" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/><p>Figure 2: Hierarchy of Schema Types used in XPath</p></div3>


<div3 id="id-typed-value"><head>Typed Value and String Value</head>

<p>Every node
has a <term>typed value</term> and a <term>string value</term>.

<termdef term="typed value" id="dt-typed-value">The <term>typed value</term> of a node is a sequence of atomic values
and can be extracted by applying the <code>fn:data</code> function to
the node.</termdef>  <termdef id="dt-string-value" term="string value">The <term>string
 value</term> of a node is a string and 
 can be extracted by applying the <code>fn:string</code>
 function to the node.</termdef>
Definitions of <code>fn:data</code> and <code>fn:string</code> can be found in <bibref ref="FunctionsAndOperators"/>.</p>


<p>An implementation may store both the <termref def="dt-typed-value">typed value</termref> and the <termref def="dt-string-value">string value</termref> of a node, or it may store only one of these and derive the other as needed. The string value of a node must be a valid lexical representation of the typed value of the node, but the node is not required to preserve the string representation from the original source document. For example, if the typed value of a node is the <code>xs:integer</code> value <code>30</code>, its string value might be "<code>30</code>" or "<code>0030</code>".</p><p role="xpath">The <termref def="dt-typed-value">typed value</termref>, <termref def="dt-string-value">string value</termref>, and <termref def="dt-type-annotation">type annotation</termref> of a node are closely related.  If the node was created by mapping from an Infoset or PSVI, the relationships among these properties are defined by rules in <bibref ref="datamodel"/>.</p><p>As a convenience to the reader, the relationship between <termref def="dt-typed-value">typed value</termref> and
 <termref def="dt-string-value">string value</termref> for various kinds of nodes is summarized and illustrated
 by examples below.</p>

<olist><item><p>For text and document nodes, the typed value of the node is the same as its
string value, as an instance of  the type <code>xs:untypedAtomic</code>. The
string value of a document node is formed by concatenating the string
values of all its descendant text nodes, in <termref def="dt-document-order">document
order</termref>.</p></item><item><p>The typed value of a comment<phrase role="xpath">, namespace,</phrase> or processing instruction node is the same as its string value. It is an instance of the type <code>xs:string</code>.</p></item><item><p>The typed value of an attribute node with
the <termref def="dt-type-annotation">type annotation</termref> <code>xs:anySimpleType</code> or <code>xs:untypedAtomic</code> is the same as its
string value, as an instance of <code>xs:untypedAtomic</code>. The
typed value of an attribute node with any other type annotation is
derived from its string value and type annotation using the lexical-to-value-space mapping defined in <bibref ref="XMLSchema"/> Part 2 for
the relevant type.</p><p>Example: A1 is an attribute
having string value <code>"3.14E-2"</code> and type annotation
<code>xs:double</code>.  The typed value of A1 is the
<code>xs:double</code> value whose lexical representation is
<code>3.14E-2</code>. </p><p>Example: A2 is an attribute with type
annotation <code>xs:IDREFS</code>, which is a list datatype whose item type is the atomic datatype <code>xs:IDREF</code>. Its string value is
"<code>bar baz faz</code>". The typed value of A2 is a sequence of
three atomic values ("<code>bar</code>", "<code>baz</code>",
"<code>faz</code>"), each of type <code>xs:IDREF</code>. The typed
value of a node is never treated as an instance of a named list
type. Instead, if the type annotation of a node is a list type (such
as <code>xs:IDREFS</code>), its typed value is treated as a sequence
of the atomic type from which it is derived (such as
<code>xs:IDREF</code>).</p></item><item><p>For an element node, the
relationship between typed value and string value depends on the
node's <termref def="dt-type-annotation">type annotation</termref>, as follows:</p><olist>

<item>

<p>If the type annotation is <code>xs:untyped</code> or <code>xs:anySimpleType</code> or
denotes a complex type with mixed content (including <code>xs:anyType</code>), then the typed value of the
node is equal to its string value, as an instance of
<code>xs:untypedAtomic</code>.  However, if the <code>nilled</code> 
property of the node is <code>true</code>, then its typed value is the empty sequence.</p>



<p>Example: E1 is an element node
having type annotation <code>xs:untyped</code> and string value
"<code>1999-05-31</code>". The typed value of E1 is
"<code>1999-05-31</code>", as an instance of
<code>xs:untypedAtomic</code>.</p>


<p>Example: E2 is an element node
with the type annotation <code>formula</code>, which is a complex type
with mixed content. The content of E2 consists of the character
"<code>H</code>", a child element named <code>subscript</code> with
string value "<code>2</code>", and the character "<code>O</code>". The
typed value of E2 is "<code>H2O</code>" as an instance of
<code>xs:untypedAtomic</code>.</p></item>

<item><p>If the type
annotation denotes a simple type or a complex type with simple
content, then the typed value of the node is derived from its string
value and its type annotation in a way that is consistent with schema
validation. However, if the <code>nilled</code> 
property of the node is <code>true</code>, then its typed value is the empty sequence.</p><p>Example: E3 is an element node with the type
annotation <code>cost</code>, which is a complex type that has several
attributes and a simple content type of <code>xs:decimal</code>. The
string value of E3 is "<code>74.95</code>". The typed value of E3 is
<code>74.95</code>, as an instance of
<code>xs:decimal</code>.</p><p>Example: E4 is an element node with the
type annotation <code>hatsizelist</code>, which is a simple type
derived from the atomic type <code>hatsize</code>, which in turn is
derived from <code>xs:integer</code>. The string value of E4 is
"<code>7 8 9</code>". The typed value of E4 is a sequence of three
values (<code>7</code>, <code>8</code>, <code>9</code>), each of type
<code>hatsize</code>.</p><p>Example: E5 is an element node with the type annotation <code>my:integer-or-string</code> which is a union type with member types <code>xs:integer</code> and <code>xs:string</code>. The string value of E5 is "<code>47</code>". The typed value of E5 is <code>47</code> as an <code>xs:integer</code>, since <code>xs:integer</code> is the member type that validated the content of E5. In general, when the type annotation of a node is a union type, the typed value of the node will be an instance of one of the member types of the union.</p><note><p>If an implementation stores only the string value of a node, and the type annotation of the node is a union type, the implementation must be able to deliver the typed value of the node as an instance of the appropriate member type.</p></note></item><item><p>If the type annotation
denotes a complex type with empty content, then the typed value of the
node is the empty sequence and its string value is the zero-length string.</p></item><item><p>If the type annotation
denotes a complex type with element-only content, then the typed value
of the node is undefined. The <code>fn:data</code> function raises a
<termref def="dt-type-error">type error</termref> [err:FOTY0012] when applied to such a node. The string value of such a node is equal to the concatenated string values of all its text node descendants, in document order.</p><p>Example: E6 is an
element node with the type annotation <code>weather</code>, which is a
complex type whose content type specifies
<code>element-only</code>. E6 has two child elements named
<code>temperature</code> and <code>precipitation</code>. The typed
value of E6 is undefined, and the <code>fn:data</code> function
applied to E6 raises an error.
</p></item></olist></item></olist></div3><div3 id="id-sequencetype-syntax"><head>SequenceType Syntax</head><p>Whenever it is necessary to refer to a type in an XPath expression, the <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-SequenceType" xlink:type="simple">SequenceType</nt> syntax is used.</p> 
		  <scrap headstyle="show"> 
			 <head/> 
			 <prod num="50" id="doc-xpath-SequenceType"><lhs>SequenceType</lhs><rhs>("empty-sequence"  "("  ")")<br/>|  (<nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-ItemType" xlink:type="simple">ItemType</nt>  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-OccurrenceIndicator" xlink:type="simple">OccurrenceIndicator</nt>?)</rhs></prod> 
			 <prod num="52" id="doc-xpath-ItemType"><lhs>ItemType</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-KindTest" xlink:type="simple">KindTest</nt>  |  ("item"  "("  ")")  |  <nt xmlns:xlink="http://www.w3.org/1999/xlink" def="doc-xpath-AtomicType" xlink:type="simple">AtomicType</nt></rhs></prod><prod num="51" id="doc-xpath-OccurrenceIndicator"><lhs>OccurrenceIndicator</lhs><rhs>"?"  |  "*"  |  "+"</rhs></prod><prod num="53" id="doc-xpath-AtomicType"><lhs>AtomicType</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="prod-xpath-QName" xlink:type="simple">QName</nt></rhs></prod> 
			 <prod num="54" id="doc-xpath-KindTest"><lhs>KindTest</lhs><rhs><nt xmlns:xlink="http://www.w3.org/1999/xlink" def="