tDOM

Check-in Differences
Login

Check-in Differences

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Difference From 98cd4affb5a91ca6 To f00c8a6439d579e8

2002-03-21
01:47
Collected the various nodeSet Result types into "nodeSetResult" (there still exists a seperate emptyResult type). Reworked xpathEvalStep. Fixed memory leak in xpathMatches, added rsAddNodeFast(), if it's known for sure, that the node to add isn't already in the nodeSet. check-in: 0e6533ac59 user: rolf tags: trunk
2002-03-16
13:06
Optimised xsl:sort: the string or numeric value of the nodes to sort are computed only once and cached for further comparisons in the sort process. check-in: f00c8a6439 user: rolf tags: trunk
2002-03-14
13:28
Fixed the Fix of the last commit. check-in: cbe771bf12 user: rolf tags: trunk
2002-02-23
01:08
Initial check in of win makefile. Tested on w2k with VC 6++ check-in: 0ce4795ef9 user: rolf tags: trunk
2002-02-22
01:05
tDOM0.7test with Jochens first set of patches Closed-Leaf check-in: 002482c973 user: rolf tags: trunk, demo
01:05
Initial revision check-in: 98cd4affb5 user: rolf tags: trunk

Changes to apps/xslt.tcl.
24
25
26
27
28
29
30



31
32
33
34
35
36
37
38
39
40


41
42




43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#   Portions created by Jochen Loewer are Copyright (C) 1998, 1999
#   Jochen Loewer. All Rights Reserved.
#
#   Contributor(s):            
#
#
#   $Log$



#   Revision 1.1  2002/02/22 01:05:34  rolf
#   Initial revision
#
#
#
#   written by Rolf Ade
#   August, 2001
#
#----------------------------------------------------------------------------



load   [file dirname [info script]]/../unix/tdom0.6.so
source [file dirname [info script]]/../lib/tdom.tcl






#----------------------------------------------------------------------------
#    externalEntityRefHandler
#
#----------------------------------------------------------------------------
proc externalEntityRefHandler { base systemId publicId } {

    # puts stderr "externalEntityRefHandler:"
    # puts stderr "\tbase $base"
    # puts stderr "\tsystemId $systemId"
    # puts stderr "\tpublicId $publicId"

    if {[regexp {^[a-zA-Z]+:/} $systemId]}  {
        # Seems to be not relative to the base
        if {[regexp { *file://(.*)} $systemId dummy path]} {
            set fd [open $path]
            fconfigure $fd -translation binary
            return [list channel $systemId $fd]
        } else {







>
>
>
|
|








>
>
|
|
>
>
>
>








<
<
<
<
<







24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59





60
61
62
63
64
65
66
#   Portions created by Jochen Loewer are Copyright (C) 1998, 1999
#   Jochen Loewer. All Rights Reserved.
#
#   Contributor(s):            
#
#
#   $Log$
#   Revision 1.2  2002/02/26 14:05:02  rolf
#   Updated the [load ...] to the new version number 0.7
#
#   Revision 1.1.1.1  2002/02/22 01:05:34  rolf
#   tDOM0.7test with Jochens first set of patches
#
#
#
#   written by Rolf Ade
#   August, 2001
#
#----------------------------------------------------------------------------

if {[catch {package require tdom} errMsg]} {
    if {[catch {
        load   [file dirname [info script]]/../unix/tdom0.7.so
        source [file dirname [info script]]/../lib/tdom.tcl
    }]} {
        puts $errMsg
    }
}


#----------------------------------------------------------------------------
#    externalEntityRefHandler
#
#----------------------------------------------------------------------------
proc externalEntityRefHandler { base systemId publicId } {






    if {[regexp {^[a-zA-Z]+:/} $systemId]}  {
        # Seems to be not relative to the base
        if {[regexp { *file://(.*)} $systemId dummy path]} {
            set fd [open $path]
            fconfigure $fd -translation binary
            return [list channel $systemId $fd]
        } else {
Deleted doc/INDEX.MAP.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

<!-- This file was automatically generated -->
<INDEX title="tDOM manual" package="tDOM">
    <MAN id="domNode" title="domNode"/>
    <DEF cat="manpage" name="domNode" manpage="domNode"/>
    <DEF cat="cmd" name="domNode" manpage="domNode"/>
    <MAN id="dom" title="dom"/>
    <DEF cat="manpage" name="dom" manpage="dom"/>
    <DEF cat="cmd" name="dom" manpage="dom"/>
    <MAN id="domDoc" title="domDoc"/>
    <DEF cat="manpage" name="domDoc" manpage="domDoc"/>
    <DEF cat="cmd" name="domDoc" manpage="domDoc"/>
    <MAN id="expat" title="expat"/>
    <DEF cat="manpage" name="expat" manpage="expat"/>
    <DEF cat="cmd" name="expat" manpage="expat"/>
    <MAN id="expatapi" title="expatapi"/>
    <DEF cat="manpage" name="expatapi" manpage="expatapi"/>
    <DEF cat="fun" name="CheckExpatParserObj, CHandlerSetInstall, CHandlerSetRemove,
         CHandlerSetCreate, CHandlerSetGetUserData, GetExpatInfo" manpage="expatapi"/>
    <MAN id="tdomcmd" title="tdom"/>
    <DEF cat="manpage" name="tdomcmd" manpage="tdomcmd"/>
    <DEF cat="cmd" name="tdom" manpage="tdomcmd"/>
    <MAN id="tnc" title="tdom"/>
    <DEF cat="manpage" name="tnc" manpage="tnc"/>
    <DEF cat="cmd" name="tnc" manpage="tnc"/>
    <KWD name="C handler set">
        <refto>expatapi</refto>
        <refto>tdomcmd</refto>
    </KWD>
    <KWD name="document">
        <refto>dom</refto>
        <refto>domNode</refto>
    </KWD>
    <KWD name="document element">
        <refto>domDoc</refto>
    </KWD>
    <KWD name="DOM">
        <refto>dom</refto>
        <refto>domNode</refto>
        <refto>tdomcmd</refto>
    </KWD>
    <KWD name="DOM node creation">
        <refto>domDoc</refto>
    </KWD>
    <KWD name="node">
        <refto>dom</refto>
        <refto>domNode</refto>
    </KWD>
    <KWD name="parsing">
        <refto>dom</refto>
        <refto>domNode</refto>
    </KWD>
    <KWD name="SAX">
        <refto>expat</refto>
        <refto>tdomcmd</refto>
    </KWD>
    <KWD name="Validation">
        <refto>tnc</refto>
    </KWD>
    <KWD name="XML">
        <refto>dom</refto>
        <refto>domNode</refto>
    </KWD>
</INDEX>

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































Changes to doc/dom.xml.
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

92
93
94
95
96
97
98
99
recommendation). That should double parsing and DOM generation speed. UTF-8 is
not generated internally with that parser. Currently this parser does not
handle namespaces.</desc>
              </optdef>

              <optdef>
                <optname>-html</optname>
                <desc>If <m>-html</m> is specified, a fast HTML parser is used, which tries
to even parse badly formed HTML into a DOM tree.</desc>
              </optdef>
       
              <optdef>
                <optname>-keepEmpties</optname> 
                <desc>If <m>-keepEmpties</m> is
specified, text nodes, which contain only whitespaces, will be part of the
resulting DOM tree. In default case (<m>-keepEmpties</m> not given) those empty
text nodes are removed at parsing time.</desc>
              </optdef>

              <optdef>
                <optname>-channel</optname>
                <optarg>&lt;channel-ID&gt;</optarg>

                <desc>If <m>-channel &lt;channel-ID&gt;</m> is specified, the
input to be parsed is read from the specified channel. The input is read from
the channel in "raw" (binary) mode from the channel, ignoring any encoding

setting via -fconfigure of the channel.</desc>
              </optdef>

              <optdef>
                <optname>-baseurl</optname>
                <optarg>&lt;baseURI&gt;</optarg>
                
                <desc>If <m>-baseurl &lt;baseURI&gt;</m> is specified, the







|
|















|
|
>
|







66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
recommendation). That should double parsing and DOM generation speed. UTF-8 is
not generated internally with that parser. Currently this parser does not
handle namespaces.</desc>
              </optdef>

              <optdef>
                <optname>-html</optname>
                <desc>If <m>-html</m> is specified, a fast HTML parser is 
used, which tries to even parse badly formed HTML into a DOM tree.</desc>
              </optdef>
       
              <optdef>
                <optname>-keepEmpties</optname> 
                <desc>If <m>-keepEmpties</m> is
specified, text nodes, which contain only whitespaces, will be part of the
resulting DOM tree. In default case (<m>-keepEmpties</m> not given) those empty
text nodes are removed at parsing time.</desc>
              </optdef>

              <optdef>
                <optname>-channel</optname>
                <optarg>&lt;channel-ID&gt;</optarg>

                <desc>If <m>-channel &lt;channel-ID&gt;</m> is specified, the
input to be parsed is read from the specified channel. The encoding setting of
the channel (via fconfigure -encoding) is respected, ie the data read from the
channel are converted to UTF-8 according to the encoding settings, befor the
data is parsed.</desc>
              </optdef>

              <optdef>
                <optname>-baseurl</optname>
                <optarg>&lt;baseURI&gt;</optarg>
                
                <desc>If <m>-baseurl &lt;baseURI&gt;</m> is specified, the
143
144
145
146
147
148
149











150
151
152
153
154
155
156

          <desc><p>Creates a new DOM document object with one element node with
node name <samp>docElemName</samp>. The <samp>objVar</samp> controlls the
memory handling as explained above.</p>
</desc>
        </commanddef>












        <commanddef>
          <command><cmd>dom</cmd> <method>setResultEncoding</method> ?<m>encodingName</m>?</command>

          <desc><p>If <samp>encodingName</samp> is not given the current global
result encoding is returned.  Otherwise the global result encoding is set to
<samp>encodingName</samp>.  All character data, attribute values, etc. will
then be converted from UTF-8, which is delivered from the Expat XML parser, to







>
>
>
>
>
>
>
>
>
>
>







144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168

          <desc><p>Creates a new DOM document object with one element node with
node name <samp>docElemName</samp>. The <samp>objVar</samp> controlls the
memory handling as explained above.</p>
</desc>
        </commanddef>

        <commanddef>
          <command><cmd>dom</cmd> <method>createDocumentNS</method>
<m>docElemName</m> <m>uri</m> ?<m>objVar</m>?</command>

          <desc><p>Creates a new DOM document object with one element node with
node name <samp>docElemName</samp>. <samp>Uri</samp> gives the namespace of the
document element to create. The <samp>objVar</samp> controlls the
memory handling as explained above.</p>
</desc>
        </commanddef>

        <commanddef>
          <command><cmd>dom</cmd> <method>setResultEncoding</method> ?<m>encodingName</m>?</command>

          <desc><p>If <samp>encodingName</samp> is not given the current global
result encoding is returned.  Otherwise the global result encoding is set to
<samp>encodingName</samp>.  All character data, attribute values, etc. will
then be converted from UTF-8, which is delivered from the Expat XML parser, to
Changes to doc/domNode.xml.
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
        <command><method>data</method></command>
        <desc> For a processing instruction node the data part is returned.
Otherwise an error is generated.</desc>
      </commanddef>

      <commanddef>
        <command><method>prefix</method></command>
        <desc> ...todo...  Returns the namespace prefix.</desc>
      </commanddef>

      <commanddef>
        <command><method>namespaceURI</method></command>
        <desc> ...todo...  Returns the URI from the namespace of the given
node.</desc>
      </commanddef>

      <commanddef>
        <command><method>namespaceURI</method></command>
        <desc> ...todo...  Returns the localName from the tag name of the given
node.</desc>
      </commanddef>

      <commanddef>
        <command><method>selectNodes</method> <m>xpathQuery</m> <option>typeVar</option></command>
        <desc> Returns the result of applying the XPath query <m>xpathQuery</m>
to the subtree. This can be a string/value, a list of strings, a list of nodes,
a list of attribute name and a list of attribute name / value pairs. If







|




|
<



|
|
<







291
292
293
294
295
296
297
298
299
300
301
302
303

304
305
306
307
308

309
310
311
312
313
314
315
        <command><method>data</method></command>
        <desc> For a processing instruction node the data part is returned.
Otherwise an error is generated.</desc>
      </commanddef>

      <commanddef>
        <command><method>prefix</method></command>
        <desc>Returns the namespace prefix.</desc>
      </commanddef>

      <commanddef>
        <command><method>namespaceURI</method></command>
        <desc>Returns the URI from the namespace of the given node.</desc>

      </commanddef>

      <commanddef>
        <command><method>localName</method></command>
        <desc>Returns the localName from the tag name of the given node.</desc>

      </commanddef>

      <commanddef>
        <command><method>selectNodes</method> <m>xpathQuery</m> <option>typeVar</option></command>
        <desc> Returns the result of applying the XPath query <m>xpathQuery</m>
to the subtree. This can be a string/value, a list of strings, a list of nodes,
a list of attribute name and a list of attribute name / value pairs. If
Deleted doc/make-index.xsl.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
<?xml version='1.0'?>
<!--
	$Id$
	Author: 	Joe English, <[email protected]>
	Created: 	2 Aug 2000; rewritten from makemap.xsl 10 Jul 2000
	Description:	Build INDEX.MAP from a <manual> or <manpage>.
-->

<xsl:stylesheet
    xmlns:xsl	= "http://www.w3.org/1999/XSL/Transform"
    version	= "1.0"
>
<xsl:output method="xml"
    doctype-public="-//jenglish//DTD TMML 0.5//EN"
    indent	= "yes"
/>
<xsl:strip-space
    elements	= "meta extensions xlh"
/>

<xsl:variable name="removeChars" select="' &#x9;&#xA;%*()[]'"/>
<xsl:variable name="lower" select="'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:variable name="upper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:variable name="keywordNodes" select="//keyword"/>

<xsl:template match="/*" priority="3">
    <xsl:value-of select="'&#xA;'"/>
    <xsl:comment> This file was automatically generated </xsl:comment>
    <xsl:value-of select="'&#xA;'"/>
    <xsl:element name="INDEX">
	<xsl:attribute name="title"><xsl:value-of select="title | @title"
	/></xsl:attribute>
	<xsl:attribute name="package"><xsl:value-of select="@package"
	/></xsl:attribute>
	<xsl:apply-templates/>
        <xsl:call-template name="keywords"/>
    </xsl:element>
</xsl:template>

<!-- Transcribe metainformation from the the manual header 
     into the index:
-->
<xsl:template match="meta//node()">
    <xsl:copy
    	><xsl:for-each select="@*"><xsl:copy/></xsl:for-each
	><xsl:apply-templates
    /></xsl:copy>
</xsl:template>

<!-- Recursively expand subdocuments:
-->
<xsl:template match="subdoc" priority="2">
    <xsl:for-each select="document(@href)/manpage">
	<xsl:call-template name="manpage"/>
    </xsl:for-each>
</xsl:template>

<xsl:template name="manpage" match="manpage" priority="2">
    <MAN id="{@id}" title="{@title}"/>
    <DEF cat="manpage" name="{@id}" manpage="{@id}"/>
    <xsl:apply-templates/>
</xsl:template>

<xsl:template match="namesection/name" priority="2">
    <xsl:element name="DEF">
	<xsl:attribute name="cat"
	    ><xsl:value-of select="ancestor::manpage/@cat"
	/></xsl:attribute>
	<xsl:attribute name="name"
	    ><xsl:value-of select="."
	/></xsl:attribute>
	<xsl:attribute name="manpage"
	    ><xsl:value-of select="ancestor::manpage/@id"
	/></xsl:attribute>
    </xsl:element>
</xsl:template>

<xsl:template match="optionlist[@scope='global']/optiondef " priority="2">
    <xsl:variable name="cat"
    	><xsl:choose
	    ><xsl:when test="@cat"><xsl:value-of select="@cat"
	    /></xsl:when
	    ><xsl:otherwise>option</xsl:otherwise
	></xsl:choose
    ></xsl:variable>
    <xsl:for-each select="./name">
	<xsl:variable name="name"
	    ><xsl:choose
		><xsl:when test="@name"><xsl:value-of select="@name"
		/></xsl:when
		><xsl:otherwise><xsl:value-of select="."
		/></xsl:otherwise
	    ></xsl:choose
	></xsl:variable>
	<DEF cat    = "{ancestor-or-self::*/@cat}"
	     name   = "{$name}"
	     manpage= "{ancestor::manpage/@id}"
	     subpart= 
	 "{ancestor-or-self::*/@cat}_{translate($name,$removeChars,'')}"
	/>
    </xsl:for-each>
</xsl:template>

<xsl:template match="syntax[@name and @cat]" priority="2">
    <DEF
	cat 	= "{@cat}"
	name 	= "{@name}"
	manpage	= "{ancestor::manpage/@id}"
	subpart	= "{@cat}_{@name}"
    />
</xsl:template>

<xsl:template match="dl[@scope='global' and @cat]/dle/dt" priority="2">
    <DEF
	cat 	= "{parent::*/@cat}"
	name 	= "{.}"
	manpage	= "{ancestor::manpage/@id}"
	subpart	= "{parent::*/@cat}_{translate(.,$removeChars,'')}"
    />
</xsl:template>

<xsl:template match="//*[@tmml='xl' and @cat and not(@scope='local')]" priority="1.5">
    <xsl:variable name="cat" select="@cat"/>
    <xsl:for-each select="./descendant::name">
	<DEF 
	    cat 	= "{$cat}"
	    name	= "{.}"
	    manpage	= "{ancestor::manpage/@id}"
	    subpart	= "{$cat}_{translate(.,$removeChars,'')}"
	/>
    </xsl:for-each>
</xsl:template>

<xsl:template name="buildKWD">
  <xsl:param name="keyword"/>
  <xsl:param name="keyword-literal"/>
  <KWD name="{$keyword-literal}">
    <xsl:for-each select="$keywordNodes[$keyword=(translate(normalize-space(.),$lower,$upper))]">
      <xsl:sort select="ancestor::manpage/@id"/>
      <refto><xsl:value-of select="ancestor::manpage/@id"/></refto>
    </xsl:for-each>
  </KWD>
</xsl:template>  

<xsl:template name="keywords">
  <xsl:for-each select="$keywordNodes">
    <xsl:sort/>
    <xsl:if test="generate-id($keywordNodes[translate(normalize-space(.),$lower,$upper)=translate(normalize-space(current()),$lower,$upper)][1])=generate-id(.)">
      <xsl:call-template name="buildKWD">
        <xsl:with-param name="keyword" select="translate(normalize-space(.),$lower,$upper)"/>
        <xsl:with-param name="keyword-literal" select="."/>
      </xsl:call-template>
    </xsl:if>
  </xsl:for-each>
</xsl:template>


<!-- By default, names in ARGLISTs and OPTIONLISTs aren't global -->
<xsl:template match = 
	"arglist[not(@scope = 'global')] | optionlist[not(@scope = 'global')]"
	priority="2"
/>

<!-- Default templates:
-->
<xsl:template match="name | *[@tmml = 'name']" priority="0.5">
    <xsl:message>Unclassified name <xsl:value-of select="."
    /> in <xsl:for-each select="ancestor-or-self::*"
    	><xsl:value-of select="name()"
	/>/</xsl:for-each>
    </xsl:message>
</xsl:template>

<xsl:template match="*" priority="0">
    <xsl:apply-templates/>
</xsl:template>
<xsl:template match="node()" priority="-0.5"/>

</xsl:stylesheet>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































































































































































































































Deleted doc/my-keyword-index.xsl.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

  <xsl:import href="navpages.xsl"/>

  <xsl:output method="html"
    doctype-public="-//W3C//DTD HTML 4.0 Transitional//EN"
    indent	= "yes"
    encoding	= "us-ascii"/>

  <xsl:variable name="removeChars" select="' &#x9;&#xA;%*()[];'"/>
  <xsl:variable name="lower" select="'abcdefghijklmnopqrstuvwxyz'"/>
  <xsl:variable name="upper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
  <xsl:variable name="keywords" select="/INDEX/KWD"/>

  <xsl:template name="header">
    <xsl:call-template name="navigation-page-header">
      <xsl:with-param name="iam" select="'KWL'"/>
    </xsl:call-template>
  </xsl:template>


  <xsl:template match="INDEX">
    <html>
      <head>
        <title><xsl:value-of select="@title"/>: Keyword Index</title>
        <link rel="stylesheet" href="manpage.css"/>
        <meta name="xsl-processor" content="{system-property('xsl:vendor')}"/>
        <meta name="generator" content="$RCSfile$ $Revision$"/>
      </head>
      <body>
        <DIV class="header">
          <xsl:call-template name="header"/>
          <xsl:call-template name="keyword-header"/>
        </DIV>
        <DIV class="body">
          <DIV class="table">
            <TABLE width="100%">
              <xsl:call-template name="keyword-list"/>
            </TABLE>
          </DIV>
        </DIV>
        <DIV class="footer">
          <xsl:call-template name="footer"/>
        </DIV>
      </body>
    </html>
  </xsl:template>

  <xsl:template name="keyword-header">
    <DIV class="navbar">
      <xsl:for-each select="$keywords">
        <xsl:sort select="@name"/>
        <xsl:variable name="indexChar" select="translate(substring(normalize-space(@name),1,1),$lower,$upper)"/>
        <xsl:if test="generate-id($keywords[$indexChar=translate(normalize-space(substring(@name,1,1)),$lower,$upper)][1])=generate-id(.)">
          <a href="#KEYWORDs-{$indexChar}">
            <xsl:value-of select="$indexChar"/>
          </a>
          <xsl:value-of select="$navsep"/>
        </xsl:if>
      </xsl:for-each>
    </DIV>      
  </xsl:template>

  <xsl:template name="keyword-list">
    <xsl:for-each select="$keywords">
      <xsl:variable name="indexChar" select="translate(substring(normalize-space(@name),1,1),$lower,$upper)"/>
      <xsl:if test="generate-id($keywords[$indexChar=translate(substring(normalize-space(@name),1,1),$lower,$upper)][1])=generate-id(.)">
        <tr class="header">
          <th colspan="2">
            <a name="KEYWORDs-{$indexChar}">Keywords: <xsl:value-of select="$indexChar"/></a>
          </th>
        </tr>
      </xsl:if>
      <tr class="row{position() mod 2}">
        <td width="35%">
          <a name="KW-{translate(@name,$removeChars,'')}">
            <xsl:value-of select="@name"/>
          </a>
        </td>
        <td width="65%">
          <xsl:for-each select="refto">
            <xsl:if test="position() > 1">
              <xsl:value-of select="$navsep"/>
            </xsl:if>
            <a href="{.}.html"><xsl:value-of select="."/></a>
          </xsl:for-each>
        </td>
      </tr>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>




<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































Deleted doc/navpages.xsl.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?xml version='1.0'?>
<!--
	$Id$
	Author: 	Joe English, <[email protected]>
	Created: 	29 Jun 2000
	Description:	Common XSL code for navigational material
-->
<xsl:stylesheet
    xmlns:xsl	= "http://www.w3.org/1999/XSL/Transform"
    xmlns:data	= "data"
    version	= "1.0"
    exclude-result-prefixes="data"
>
<xsl:variable name="navsep"> &#183; </xsl:variable>
<xsl:variable name="stylesheetData" select="document('')//data:data"/>


<!-- template navigation-page-header: -->

<xsl:template name="navigation-page-header">
    <xsl:param name="iam"/>
    <h1 class="title" align="center"
	><xsl:value-of select="/*/title | /*/@title"
	/>: <xsl:value-of select="$stylesheetData//navpage[@id=$iam]/@title"
    /></h1>
    <p class="navaid" align="center">
	<xsl:for-each select="$stylesheetData//navpages/navpage"
	    ><a class="navaid" href="{@href}"><xsl:value-of select="@title"/></a
	    ><xsl:if test="following-sibling::navpage"
	    	><xsl:value-of select="$navsep"
	    /></xsl:if
	></xsl:for-each>
    </p>
    <hr class="navsep"/>
</xsl:template>

<xsl:template name="footer">
    <hr class="navsep"/>
    <xsl:copy-of select="document('footer.xml')"/>
</xsl:template>

<data:data>
<navpages>
  <navpage id="TOC" title="Table of Contents"	href="index.html"/>
  <navpage id="CAT" title="Index"		href="category-index.html"/>
  <navpage id="KWL" title="Keywords"		href="keyword-index.html"/>
</navpages>
</data:data>

<!-- Default catch-all rule, used to catch source elements
     for which there is no matching template:
     Usage: 
     	template match="*" priority="-1" 
	    call-template name="catchall"
-->
<xsl:variable name="debug" select="1"/>
<xsl:template name="catchall"
    ><xsl:message terminate="no">Unrecognized GI <xsl:value-of select="name()"
    /></xsl:message
    ><xsl:choose
	><xsl:when test="$debug"
	    ><xsl:element name="EM"
		><xsl:attribute name="class">UNRECOGNIZED</xsl:attribute
		><xsl:processing-instruction name="UNRECOGNIZED"
		    ><xsl:value-of select="name()"
		/></xsl:processing-instruction
		><xsl:apply-templates
	    /></xsl:element
	></xsl:when
	><xsl:otherwise><xsl:apply-templates/></xsl:otherwise
    ></xsl:choose
></xsl:template>

</xsl:stylesheet>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































Deleted doc/tmml.dtd.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<!--
    $Id$

    Author:	Joe English, <[email protected]>
    Created:	8 Feb 1999
    Revised:	24 Jul 1999
    Usage:

    <!DOCTYPE  (manpage | manual)  PUBLIC "-//jenglish//DTD TMML 0.6//EN" >

    Proposed XML DTD for TMML, version 0.6.

    See  <URL: http://www.flightlab.com/~joe/tmml/ > for more information.
-->

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

    Information pool parameter entities:

    e.syntax 	Phrase-level elements that refer to Tcl syntactic entities.
    e.phrase	Other phrase-level elements
    e.block	Block-level elements
    e.struct	Structural elements that can appear directly in a section

    x.block
    x.inline	Used for customization
-->

<!ENTITY % e.syntax
    " m | l | o | i | b
    | br
    | term
    | cmd | variable | method | option | file
    | syscmd | fun | widget | package | type | class
    ">

<!ENTITY % e.phrase
    " emph | ref | url | samp | command | new">

<!ENTITY % e.block
    " p | ul | ol | dl | sl | xl
    | example | syntax
    | commandlist | optlist
    " >

<!ENTITY % e.struct
    "arglist | optionlist" >

<!ENTITY % x.inline	"" >
<!ENTITY % x.block 	"" >

<!-- ============================================================
    Content models:

    m.code	(computer) text
    m.inline	inline text
    m.mixed	mixed inline and block elements
    m.top	top-level elements (inside sections)
-->

<!ENTITY % m.inline
	"(#PCDATA | %e.phrase; | %e.syntax;		%x.inline; )*">
<!ENTITY % m.code
	"(#PCDATA | new        | %e.syntax;             %x.inline; )*">
<!ENTITY % m.mixed
	"(#PCDATA | %e.phrase; | %e.syntax; | %e.block;	%x.block; %x.inline;)*">
<!ENTITY % m.top
	"(%e.block; | %e.struct; 			%x.block;)*">

<!-- ============================================================
	Common attributes:
-->

<!ENTITY % a.version	"version CDATA #IMPLIED" >
<!ENTITY % ad.scope	"scope (local|global)" >

<!-- ============================================================
	Top-level element: manual
-->

<!ENTITY % m.division
	"(title, meta?, (division* | (manpage|subdoc|extref)* ))" >

<!ENTITY % m.manual "%m.division;"				>

<!ELEMENT manual 	%m.manual;	>
<!ELEMENT division 	%m.division;	>
<!ELEMENT subdoc	EMPTY		>
<!ELEMENT extref	EMPTY		>

<!ATTLIST manual
	package		CDATA	#REQUIRED
	version		CDATA	#IMPLIED
>
<!ATTLIST extref
	href		CDATA	#REQUIRED
	title		CDATA	#REQUIRED
	type		CDATA	#REQUIRED
>
<!ATTLIST subdoc
	href		CDATA	#REQUIRED
>

<!-- ============================================================
	Top-level element: manpage
-->

<!ELEMENT manpage
	(namesection, synopsis?,
	 section*,
	 seealso?, keywords?)
>

<!ATTLIST manpage
	id  		ID	#REQUIRED
	cat  		CDATA	#REQUIRED
	title 		CDATA	#REQUIRED
	package 	CDATA	#IMPLIED
	%a.version;
>

<!ELEMENT section  (title, %m.top;, (subsection*)) >
<!ATTLIST section
	id	ID	#IMPLIED
	%a.version;
>
<!ELEMENT subsection  (title, %m.top;) >
<!ATTLIST subsection
	id	ID	#IMPLIED
	%a.version;
>

<!-- ============================================================
	Standard sections:
-->

<!ELEMENT namesection 	((name+ | (title,name*)), desc)	>
<!ELEMENT synopsis	(syntax|example)+ 		>
<!ELEMENT keywords	(keyword+)			>
<!ELEMENT keyword	(#PCDATA)			>
<!ELEMENT seealso	(ref|url)+			>

<!-- ============================================================
	Common Constructs
-->

<!ELEMENT title   	(#PCDATA) 	>
<!ELEMENT name 		(#PCDATA)	>
<!ELEMENT desc		%m.mixed;	>
<!-- OR: desc: %m.inline;  description:  %m.mixed; -->

<!ATTLIST name
	name	CDATA	#IMPLIED
	cat	CDATA	#IMPLIED
>

<!-- ============================================================
	Block-level elements:
-->

<!ELEMENT ul	(li+)		>
<!ELEMENT ol	(li+)		>
<!ELEMENT li	%m.mixed;	>
<!ATTLIST li	%a.version;	>

<!ELEMENT sl	(li+)		>
<!ATTLIST sl
	cols	CDATA	#IMPLIED
	cat 	CDATA	#IMPLIED
>

<!ELEMENT dl	(dle+)		>  <!-- OR: (dle+ | (dt, dd)+) -->
<!ELEMENT dle	(dt+, dd)	>
<!ATTLIST dle	%a.version; 	>
<!ELEMENT dt	%m.inline;	>
<!ELEMENT dd	%m.mixed; 	>
<!ATTLIST dl
	scope	(local|global)	"local"
	cat	CDATA		#IMPLIED
>

<!-- Extended lists:  
     Similar to DocBook SegmentedLists
-->

<!ELEMENT xl	(xlh?, xle+)	>
<!ELEMENT xlh	(xh+) 		>
<!ELEMENT xh	%m.inline;	>
<!ELEMENT xle	(xt+, desc?)	>
<!ELEMENT xt	%m.inline;	>

<!ELEMENT p	%m.inline; 	>
<!ATTLIST p	%a.version;	>

<!ELEMENT example	%m.code;			>
<!ELEMENT syntax	%m.code;			>
<!ATTLIST syntax
	%ad.scope;	#IMPLIED
	cat	CDATA	#IMPLIED
	name    CDATA	#IMPLIED
>

<!-- ============================================================
	Inline elements:
-->

<!ELEMENT i	%m.inline;	>
<!ATTLIST i	cat CDATA #IMPLIED >
<!ELEMENT b	%m.inline;	>
<!ATTLIST b	cat CDATA #IMPLIED >
<!ELEMENT emph	%m.inline;	>
<!ELEMENT samp	%m.code;	>
<!ELEMENT o	%m.code;	>

<!ELEMENT url	(#PCDATA)	>
<!ELEMENT ref	(#PCDATA)	>
<!ATTLIST ref
	refid	CDATA	#IMPLIED
	href	CDATA	#IMPLIED

	cat	CDATA	#IMPLIED
>
<!-- @@ ALSO:
	package	CDATA	#IMPLIED
	manpage	CDATA	#IMPLIED
	cat	CDATA	#IMPLIED
	name	CDATA	#IMPLIED
Legal combinations: (package? & ((manpage? & refid?) | (name? & cat?)))
-->

<!ELEMENT new	%m.inline;>
<!ATTLIST new
    version	CDATA	#REQUIRED
>

<!ELEMENT br	EMPTY	>

<!-- ============================================================
	Syntax elements:
-->

<!ELEMENT m (#PCDATA) >
<!ELEMENT l (#PCDATA) >

<!ELEMENT term (#PCDATA) >
<!ATTLIST term
	cat 	CDATA 	#IMPLIED
>
<!ELEMENT cmd   	(#PCDATA)	>
<!ELEMENT method 	(#PCDATA) 	>
<!ELEMENT option	(#PCDATA) 	>
<!ELEMENT syscmd 	(#PCDATA)	>
<!ELEMENT widget 	(#PCDATA)	>
<!ELEMENT fun   	(#PCDATA)	>
<!ELEMENT variable 	(#PCDATA)	>
<!ELEMENT package 	(#PCDATA)	>
<!ELEMENT type  	(#PCDATA)	>
<!ELEMENT class  	(#PCDATA)	>
<!ELEMENT file  	(#PCDATA)	>

<!-- ============================================================
	Tcl entity definition elements:
-->

<!ELEMENT arglist (argdef+) 		>
<!ELEMENT argdef (argtype, name, argmode?, desc)	>
<!ATTLIST argdef
	%a.version;
>
<!ELEMENT argtype 	(#PCDATA)>
<!ELEMENT argmode 	(#PCDATA)>

<!ELEMENT commandlist	(commanddef+) >
<!ELEMENT commanddef	(command,desc) >
<!ATTLIST commanddef	%a.version; >
<!ELEMENT command 	%m.code; >

<!ELEMENT optlist	(optdef+) >
<!ELEMENT optdef	(optname,optarg?,desc) >
<!ELEMENT optname 	(#PCDATA) >
<!ELEMENT optarg 	(#PCDATA) >

<!ELEMENT optionlist	(optiondef+) >
<!ELEMENT optiondef	(name, dbname, dbclass, desc) >
<!ATTLIST optiondef	%a.version; >
<!ELEMENT dbname	(#PCDATA) >
<!ELEMENT dbclass	(#PCDATA) >
<!ATTLIST optionlist
	%ad.scope; "local"
	cat 	CDATA		#IMPLIED
>

<!-- ============================================================
	#FIXED attributes:
	A DTD-aware processor may take advantage of these
	if it simplifies processing.
-->
<![IGNORE[
<!ENTITY % lineSpecific	"xml:space (default|preserve) 'preserve'" >
<!ENTITY % tmmlform	"tmml CDATA #FIXED" >
<!ENTITY % tmmlcat	"cat  CDATA #FIXED" >

<!ATTLIST namesection	%tmmlform; "section"	title CDATA #FIXED "NAME" >
<!ATTLIST synopsis	%tmmlform; "section"	title CDATA #FIXED "SYNOPSIS" >
<!ATTLIST keywords	%tmmlform; "section"	title CDATA #FIXED "KEYWORDS" >
<!ATTLIST seealso	%tmmlform; "section"	title CDATA #FIXED "SEE ALSO" >
<!ATTLIST optionlist	%tmmlform; "xl" >
<!ATTLIST arglist	%tmmlform; "xl" >
<!ATTLIST example 	%lineSpecific; >
<!ATTLIST syntax	%lineSpecific; >
<!ATTLIST cmd   	%tmmlform; "term"	%tmmlcat; "cmd" >
<!ATTLIST method  	%tmmlform; "term"	%tmmlcat; "method " >
<!ATTLIST option 	%tmmlform; "term"	%tmmlcat; "option" >
<!ATTLIST syscmd 	%tmmlform; "term"	%tmmlcat; "syscmd" >
<!ATTLIST widget 	%tmmlform; "term"	%tmmlcat; "widget" >
<!ATTLIST fun   	%tmmlform; "term"	%tmmlcat; "fun" >
<!ATTLIST variable 	%tmmlform; "term"	%tmmlcat; "variable" >
<!ATTLIST package 	%tmmlform; "term"	%tmmlcat; "package" >
<!ATTLIST type    	%tmmlform; "term"	%tmmlcat; "type" >
<!ATTLIST class    	%tmmlform; "term"	%tmmlcat; "class" >
<!ATTLIST file    	%tmmlform; "term"	%tmmlcat; "file" >
]]>

<!-- ============================================================
	Metainformation:
	Note that these elements do not normally appear
	inside TMML documents; they're for administrative
	purposes only.
-->

<!ELEMENT meta 		(extensions?) >
<!ELEMENT extensions	((extension|xlh)*) >
<!ELEMENT extension	EMPTY >
<!ATTLIST extension
    gi		CDATA	#REQUIRED
    tmml	CDATA	#REQUIRED
>
<!ATTLIST xlh
	gi	CDATA	#IMPLIED
>

<![INCLUDE[
<!ELEMENT categories 	(category+) >
<!ELEMENT category	EMPTY >
<!ATTLIST category
	id  	ID	#REQUIRED
	title	CDATA	#IMPLIED
>

<!ENTITY categories
    PUBLIC "-//jenglish//DOCUMENT Default TMML Categories" "categories.xml"
>

<!ELEMENT INDEX (meta?, (MAN|DEF|KWD)*) >
<!ATTLIST INDEX
	package	CDATA	#IMPLIED
	title	CDATA	#REQUIRED
>

<!ELEMENT DEF	EMPTY  >
<!ATTLIST DEF
	name	CDATA	#REQUIRED
	cat	CDATA	#IMPLIED
	package	CDATA	#IMPLIED
	manpage	CDATA	#IMPLIED
	subpart	CDATA	#IMPLIED
>
<!ELEMENT KWD	(refto+)  >
<!ATTLIST KWD
	name	CDATA	#REQUIRED
>

<!ELEMENT refto (#PCDATA) >

<!ELEMENT MAN	EMPTY  >
<!ATTLIST MAN
	id	CDATA	#REQUIRED
	title	CDATA	#REQUIRED
>

]]>
<!-- EOF -->
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































































































































































































































































































































































































































































































































Changes to extensions/tnc/tnc.c.
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
        "Can only handle UTF8 chars up to 3 bytes length."
    };
    if (code > 0 && code < sizeof(message)/sizeof(message[0]))
        return message[code];
    return 0;
}


#define UTF8_1BYTE_CHAR(c) ( 0    == ((c) & 0x80))
#define UTF8_2BYTE_CHAR(c) ( 0xC0 == ((c) & 0xC0))
#define UTF8_3BYTE_CHAR(c) ( 0xE0 == ((c) & 0xE0))
#define UTF8_4BYTE_CHAR(c) ( 0xF0 == ((c) & 0xF0))

/* The following 2 defines are out of the expat code */

/* A 2 byte UTF-8 representation splits the characters 11 bits
between the bottom 5 and 6 bits of the bytes.
We need 8 bits to index into pages, 3 bits to add to that index and
5 bits to generate the mask. */







<

|
|
|







174
175
176
177
178
179
180

181
182
183
184
185
186
187
188
189
190
191
        "Can only handle UTF8 chars up to 3 bytes length."
    };
    if (code > 0 && code < sizeof(message)/sizeof(message[0]))
        return message[code];
    return 0;
}


#define UTF8_1BYTE_CHAR(c) ( 0    == ((c) & 0x80))
#define UTF8_2BYTE_CHAR(c) ( 0xC0 == ((c) & 0xE0))
#define UTF8_3BYTE_CHAR(c) ( 0xE0 == ((c) & 0xF0))
#define UTF8_4BYTE_CHAR(c) ( 0xF0 == ((c) & 0xF8))

/* The following 2 defines are out of the expat code */

/* A 2 byte UTF-8 representation splits the characters 11 bits
between the bottom 5 and 6 bits of the bytes.
We need 8 bits to index into pages, 3 bits to add to that index and
5 bits to generate the mask. */
Changes to generic/dom.c.
32
33
34
35
36
37
38



















39
40
41
42
43
44
45
46
47
|       June00  Zoran Vasiljevic  Made thread-safe.
|
|           01  Rolf Ade          baseURI stuff, ID support, external 
|                                 entities, tdom command
|
|
|   $Log$



















|   Revision 1.1  2002/02/22 01:05:34  rolf
|   Initial revision
|
|
|
|   written by Jochen Loewer
|   April 5, 1999
|
\--------------------------------------------------------------------------*/







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|







32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|       June00  Zoran Vasiljevic  Made thread-safe.
|
|           01  Rolf Ade          baseURI stuff, ID support, external 
|                                 entities, tdom command
|
|
|   $Log$
|   Revision 1.6  2002/03/10 01:16:12  rolf
|   Added support for [dom createDocumentNS]. Added tests for correctness
|   of document Element tag name.
|
|   Revision 1.5  2002/03/07 22:11:32  rolf
|   Freeze of actual state, befor feeding stuff to Jochen.
|
|   Revision 1.4  2002/03/01 01:30:20  rolf
|   No real code changes. Only to log additional change in 1.3:
|   Fixed namespace overflow throu repeated (identical in prefix and uri)
|   namespace declarations.
|
|   Revision 1.3  2002/03/01 01:18:22  rolf
|   Changed parsing. [dom parse ..] now uses Tcl_GetStringFromObj(),
|   dom parse -channel now respects the encoding of the channel.
|
|   Revision 1.2  2002/02/23 01:13:33  rolf
|   Some code tweaking for a mostly warning free MS build
|
|   Revision 1.1.1.1  2002/02/22 01:05:34  rolf
|   tDOM0.7test with Jochens first set of patches
|
|
|
|   written by Jochen Loewer
|   April 5, 1999
|
\--------------------------------------------------------------------------*/
243
244
245
246
247
248
249












































250
251
252
253
254
255
256
    return (domTextNode *)n;
}

domProcessingInstructionNode * coerceToProcessingInstructionNode( domNode *n ) {
    return (domProcessingInstructionNode *)n;
}














































/*---------------------------------------------------------------------------
|   domLookupNamespace
|
\--------------------------------------------------------------------------*/
domNS *
domLookupNamespace (







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
    return (domTextNode *)n;
}

domProcessingInstructionNode * coerceToProcessingInstructionNode( domNode *n ) {
    return (domProcessingInstructionNode *)n;
}

/*---------------------------------------------------------------------------
|   domIsNAME
|
\--------------------------------------------------------------------------*/
static int
domIsNAME (
    char *name
    )
{
    char *p;
    
    p = name;
    if (!isNameStart(p)) return 0;
    p += UTF8_CHAR_LEN(*p);
    while (*p) {
        if (isNameChar(p)) 
            p += UTF8_CHAR_LEN(*p);
        else return 0;
    }
    return 1;
}


/*---------------------------------------------------------------------------
|   domIsNCNAME
|
\--------------------------------------------------------------------------*/
static int
domIsNCNAME (
    char *name
    )
{
    char *p;
    
    p = name;
    if (!isNCNameStart(p)) return 0;
    p += UTF8_CHAR_LEN(*p);
    while (*p) {
        if (isNCNameChar(p)) 
            p += UTF8_CHAR_LEN(*p);
        else return 0;
    }
    return 1;
}

/*---------------------------------------------------------------------------
|   domLookupNamespace
|
\--------------------------------------------------------------------------*/
domNS *
domLookupNamespace (
295
296
297
298
299
300
301




























302
303
304
305
306
307
308
            return ns;
        }
        ns = ns->next;
    }
    return NULL;
}






























/*---------------------------------------------------------------------------
|   domLookupURI
|
\--------------------------------------------------------------------------*/
domNS *
domLookupURI (







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
            return ns;
        }
        ns = ns->next;
    }
    return NULL;
}

/*---------------------------------------------------------------------------
|   domIsNamespaceInScope
|
\--------------------------------------------------------------------------*/
int 
domIsNamespaceInScope (
    domActiveNS *NSstack,
    int          NSstackPos,
    char        *prefix,
    char        *namespaceURI
    )
{
    int    i;
    
    for (i = NSstackPos; i >= 0; i--) {
        if (strcmp(NSstack[i].namespace->prefix, prefix)==0) {
            if (strcmp(NSstack[i].namespace->uri, namespaceURI)==0) {
                /* OK, exactly the same namespace declaration is in scope */
                return 1;
            } else {
                /* This prefix is currently assigned to another uri,
                   we need a new NS declaration, to override this one */
                return 0;
            }
        }
    }
    return 0;
}

/*---------------------------------------------------------------------------
|   domLookupURI
|
\--------------------------------------------------------------------------*/
domNS *
domLookupURI (
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
{
    domReadInfo   *info = userData;
    domNode       *node, *parentNode, *toplevel;
    domLineColumn *lc;
    domAttrNode   *attrnode, *lastAttr;
    const char   **atPtr, **idAttPtr;
    Tcl_HashEntry *h;
    int            hnew, len, pos, idatt;
    char          *xmlns, *localname;
    char           tagPrefix[MAX_PREFIX_LEN];
    char           prefix[MAX_PREFIX_LEN];    
    domNS         *ns;
    char           feedbackCmd[24];
    GetTDomTSD();








|







622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
{
    domReadInfo   *info = userData;
    domNode       *node, *parentNode, *toplevel;
    domLineColumn *lc;
    domAttrNode   *attrnode, *lastAttr;
    const char   **atPtr, **idAttPtr;
    Tcl_HashEntry *h;
    int            hnew, len, pos, idatt, newNSdecls;
    char          *xmlns, *localname;
    char           tagPrefix[MAX_PREFIX_LEN];
    char           prefix[MAX_PREFIX_LEN];    
    domNS         *ns;
    char           feedbackCmd[24];
    GetTDomTSD();

611
612
613
614
615
616
617

618
619
620
621
622



623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639

640
641
642
643
644
645
646
647
648
649
    

    /*--------------------------------------------------------------
    |   process namespace declarations
    |
    \-------------------------------------------------------------*/    
#ifdef TDOM_NS    

    for (atPtr = atts; atPtr[0] && atPtr[1]; atPtr += 2) {

        if (strncmp((char *)atPtr[0], "xmlns", 5) == 0) {
            xmlns = (char *)atPtr[0];
            if (xmlns[5] == ':') {



                ns = domNewNamespace(info->document, &(xmlns[6]), (char *)atPtr[1]);
            } else {
                ns = domNewNamespace(info->document, "", (char *)atPtr[1]);
            }
            /* push active namespace */
            info->activeNSpos++;
            if (info->activeNSpos >= info->activeNSsize) {
                info->activeNS = (domActiveNS*) Tcl_Realloc(
                                     (char*)info->activeNS, 
                                     sizeof(domActiveNS) * 2 * info->activeNSsize);
                info->activeNSsize = 2 * info->activeNSsize;
            }
            info->activeNS[info->activeNSpos].depth     = info->depth;
            info->activeNS[info->activeNSpos].namespace = ns;
            continue;
        } 
    }

#endif        

#ifdef TDOM_NS    
    /*----------------------------------------------------------
    |   look for namespace of element
    \---------------------------------------------------------*/
    domSplitQName ((char*)name, tagPrefix, &localname);
    for (pos = info->activeNSpos; pos >= 0; pos--) {
        if (  ((tagPrefix[0] == '\0') && (info->activeNS[pos].namespace->prefix[0] == '\0')) 
           || ((tagPrefix[0] != '\0') && (info->activeNS[pos].namespace->prefix[0] != '\0')







>





>
>
>














|


>
|
|
|







702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
    

    /*--------------------------------------------------------------
    |   process namespace declarations
    |
    \-------------------------------------------------------------*/    
#ifdef TDOM_NS    
    newNSdecls = 0;
    for (atPtr = atts; atPtr[0] && atPtr[1]; atPtr += 2) {

        if (strncmp((char *)atPtr[0], "xmlns", 5) == 0) {
            xmlns = (char *)atPtr[0];
            if (xmlns[5] == ':') {
                if (domIsNamespaceInScope (info->activeNS, info->activeNSpos,
                                           &(xmlns[6]), (char *)atPtr[1])) 
                    continue;
                ns = domNewNamespace(info->document, &(xmlns[6]), (char *)atPtr[1]);
            } else {
                ns = domNewNamespace(info->document, "", (char *)atPtr[1]);
            }
            /* push active namespace */
            info->activeNSpos++;
            if (info->activeNSpos >= info->activeNSsize) {
                info->activeNS = (domActiveNS*) Tcl_Realloc(
                                     (char*)info->activeNS, 
                                     sizeof(domActiveNS) * 2 * info->activeNSsize);
                info->activeNSsize = 2 * info->activeNSsize;
            }
            info->activeNS[info->activeNSpos].depth     = info->depth;
            info->activeNS[info->activeNSpos].namespace = ns;
            newNSdecls++;
        } 
    }
    if (newNSdecls) {
        
    }
    
    /*----------------------------------------------------------
    |   look for namespace of element
    \---------------------------------------------------------*/
    domSplitQName ((char*)name, tagPrefix, &localname);
    for (pos = info->activeNSpos; pos >= 0; pos--) {
        if (  ((tagPrefix[0] == '\0') && (info->activeNS[pos].namespace->prefix[0] == '\0')) 
           || ((tagPrefix[0] != '\0') && (info->activeNS[pos].namespace->prefix[0] != '\0')
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069

1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094

1095
1096
1097
1098
1099
1100
1101
} 

/*---------------------------------------------------------------------------
|  entityDeclHandler 
|  
\--------------------------------------------------------------------------*/
static void
entityDeclHandler (userData, entityName, is_parameter_entity, value,
                       value_length, base, systemId, publicId, notationName)
    void *userData;
    const char *entityName;
    int is_parameter_entity;
    const char *value;
    int value_length;
    const char *base;
    const char *systemId;
    const char *publicId;
    const char *notationName;

{
    domReadInfo                  *info = (domReadInfo *) userData;
    Tcl_HashEntry                *entryPtr;
    int                           hnew;

    if (notationName) {
        entryPtr = Tcl_CreateHashEntry (info->document->unparsedEntities,
                                        entityName, &hnew);
        if (hnew) {
            Tcl_SetHashValue (entryPtr, strdup (systemId));
        }
    }
}

/*---------------------------------------------------------------------------
|  externalEntityRefHandler
|  
\--------------------------------------------------------------------------*/
static int
externalEntityRefHandler (parser, openEntityNames, base, systemId, publicId)
     XML_Parser parser;
     CONST char *openEntityNames;
     CONST char *base;
     CONST char *systemId;
     CONST char *publicId;

{
    domReadInfo   *info = (domReadInfo *) XML_GetUserData (parser);

    Tcl_Obj *cmdPtr, *resultObj, *resultTypeObj, *extbaseObj, *xmlstringObj;
    Tcl_Obj *channelIdObj;
    int result, len, mode, done;
    XML_Parser extparser, oldparser = NULL;







|
<
|
|
|
|
|
|
|
|
|
>



















|
|
|
|
|
|
>







1148
1149
1150
1151
1152
1153
1154
1155

1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
} 

/*---------------------------------------------------------------------------
|  entityDeclHandler 
|  
\--------------------------------------------------------------------------*/
static void
entityDeclHandler (

    void       *userData, 
    const char *entityName,
    int         is_parameter_entity,
    const char *value,
    int         value_length,
    const char *base,
    const char *systemId,
    const char *publicId,
    const char *notationName
)
{
    domReadInfo                  *info = (domReadInfo *) userData;
    Tcl_HashEntry                *entryPtr;
    int                           hnew;

    if (notationName) {
        entryPtr = Tcl_CreateHashEntry (info->document->unparsedEntities,
                                        entityName, &hnew);
        if (hnew) {
            Tcl_SetHashValue (entryPtr, strdup (systemId));
        }
    }
}

/*---------------------------------------------------------------------------
|  externalEntityRefHandler
|  
\--------------------------------------------------------------------------*/
static int
externalEntityRefHandler (
    XML_Parser  parser,
    CONST char *openEntityNames,
    CONST char *base,
    CONST char *systemId,
    CONST char *publicId
)
{
    domReadInfo   *info = (domReadInfo *) XML_GetUserData (parser);

    Tcl_Obj *cmdPtr, *resultObj, *resultTypeObj, *extbaseObj, *xmlstringObj;
    Tcl_Obj *channelIdObj;
    int result, len, mode, done;
    XML_Parser extparser, oldparser = NULL;
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244

1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257

1258
1259
1260
1261
1262
1263
1264
}

/*---------------------------------------------------------------------------
|   startDoctypeDeclHandler   
|
\--------------------------------------------------------------------------*/
void 
startDoctypeDeclHandler (userData, doctypeName, sysid, pubid, has_internal_subset)
    void       *userData;
    const char *doctypeName;
    const char *sysid;
    const char *pubid;
    int         has_internal_subset;

{
    domReadInfo                  *info = (domReadInfo *) userData;
    
    info->insideDTD = 1;
}

/*---------------------------------------------------------------------------
|   endDoctypeDeclHandler
|
\--------------------------------------------------------------------------*/
void
endDoctypeDeclHandler (userData)
    void *userData;

{
    domReadInfo                  *info = (domReadInfo *) userData;

    info->insideDTD = 0;
}

/*---------------------------------------------------------------------------







|
|
|
|
|
|
>











|
|
>







1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
}

/*---------------------------------------------------------------------------
|   startDoctypeDeclHandler   
|
\--------------------------------------------------------------------------*/
void 
startDoctypeDeclHandler (
    void       *userData,
    const char *doctypeName,
    const char *sysid,
    const char *pubid,
    int         has_internal_subset
)
{
    domReadInfo                  *info = (domReadInfo *) userData;
    
    info->insideDTD = 1;
}

/*---------------------------------------------------------------------------
|   endDoctypeDeclHandler
|
\--------------------------------------------------------------------------*/
void
endDoctypeDeclHandler (
    void *userData
)
{
    domReadInfo                  *info = (domReadInfo *) userData;

    info->insideDTD = 0;
}

/*---------------------------------------------------------------------------
1282
1283
1284
1285
1286
1287
1288






1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303

1304
1305
1306

1307
1308
1309
1310
1311
1312
1313
{
    Tcl_HashEntry *h;
    domLineColumn *lc;
    domNode       *rootNode;
    int            hnew, done, len;
    domReadInfo    info;
    char           buf[1024];






    domDocument   *doc  = (domDocument*) Tcl_Alloc(sizeof(domDocument));
    GetTDomTSD();

  
    if (!TSDPTR(domModuleIsInitialized)) {
        domModuleInitialize();
    }

    memset(doc, 0, sizeof(domDocument));  
    doc->nodeType         = DOCUMENT_NODE;
    if (encoding_8bit) doc->nodeFlags |= USE_8_BIT_ENCODING;
    doc->documentNumber   = ++TSDPTR(domUniqueDocNr);
    doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->baseURIs         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));

    Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->unparsedEntities, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->baseURIs, TCL_ONE_WORD_KEYS);

    doc->extResolver      = extResolver;

    info.parser               = parser;
    info.document             = doc;
    info.currentNode          = NULL;
    info.depth                = 0;
    info.ignoreWhiteSpaces    = ignoreWhiteSpaces;







>
>
>
>
>
>















>



>







1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
{
    Tcl_HashEntry *h;
    domLineColumn *lc;
    domNode       *rootNode;
    int            hnew, done, len;
    domReadInfo    info;
    char           buf[1024];
#if !TclOnly8Bits    
    Tcl_Obj       *bufObj;
    Tcl_DString    dStr;
    int            useBinary;
    char          *str;
#endif
    domDocument   *doc  = (domDocument*) Tcl_Alloc(sizeof(domDocument));
    GetTDomTSD();

  
    if (!TSDPTR(domModuleIsInitialized)) {
        domModuleInitialize();
    }

    memset(doc, 0, sizeof(domDocument));  
    doc->nodeType         = DOCUMENT_NODE;
    if (encoding_8bit) doc->nodeFlags |= USE_8_BIT_ENCODING;
    doc->documentNumber   = ++TSDPTR(domUniqueDocNr);
    doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->baseURIs         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->NSscopes         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->unparsedEntities, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->baseURIs, TCL_ONE_WORD_KEYS);
    Tcl_InitHashTable (doc->NSscopes, TCL_ONE_WORD_KEYS);
    doc->extResolver      = extResolver;

    info.parser               = parser;
    info.document             = doc;
    info.currentNode          = NULL;
    info.depth                = 0;
    info.ignoreWhiteSpaces    = ignoreWhiteSpaces;
1374
1375
1376
1377
1378
1379
1380


































1381
1382
1383
1384
1385
1386
1387
1388

1389
1390
1391
1392
1393
1394
1395

    if (channel == NULL) {
        if (!XML_Parse(parser, xml, length, 1)) {
            Tcl_Free ( (char*) info.activeNS );
            return NULL;
        }
    } else {


































        do {
            len = Tcl_Read (channel, buf, sizeof(buf));
            done = len < sizeof(buf);
            if (!XML_Parse (parser, buf, len, done)) {
                Tcl_Free ( (char*) info.activeNS );
                return NULL;
            }
        } while (!done);

    }
    Tcl_Free ( (char*) info.activeNS );

    rootNode->firstChild = doc->documentElement;
    while (rootNode->firstChild->previousSibling) {
        rootNode->firstChild = rootNode->firstChild->previousSibling;
    }







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








>







1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537

    if (channel == NULL) {
        if (!XML_Parse(parser, xml, length, 1)) {
            Tcl_Free ( (char*) info.activeNS );
            return NULL;
        }
    } else {
#if !TclOnly8Bits
        Tcl_DStringInit (&dStr);
        if (Tcl_GetChannelOption (interp, channel, "-encoding", &dStr) != TCL_OK) {
            Tcl_Free ( (char*) info.activeNS );
            return NULL;
        }
        if (strcmp (Tcl_DStringValue (&dStr), "binary")==0 ) useBinary = 1;
        else useBinary = 0;
        Tcl_DStringFree (&dStr);
        if (useBinary) {
            do {
                len = Tcl_Read (channel, buf, sizeof(buf));
                done = len < sizeof(buf);
                if (!XML_Parse (parser, buf, len, done)) {
                    Tcl_Free ( (char*) info.activeNS );
                    return NULL;
                }
            } while (!done);
        } else {
            bufObj = Tcl_NewObj();
            Tcl_SetObjLength (bufObj, 6144);
            do {
                len = Tcl_ReadChars (channel, bufObj, 1024, 0);
                done = (len < 1024);
                str = Tcl_GetStringFromObj (bufObj, &len);
                if (!XML_Parse (parser, str, len, done)) {
                    Tcl_Free ( (char*) info.activeNS );
                    Tcl_DecrRefCount (bufObj);
                    return NULL;
                }
            } while (!done);
            Tcl_DecrRefCount (bufObj);
        }
#else             
        do {
            len = Tcl_Read (channel, buf, sizeof(buf));
            done = len < sizeof(buf);
            if (!XML_Parse (parser, buf, len, done)) {
                Tcl_Free ( (char*) info.activeNS );
                return NULL;
            }
        } while (!done);
#endif        
    }
    Tcl_Free ( (char*) info.activeNS );

    rootNode->firstChild = doc->documentElement;
    while (rootNode->firstChild->previousSibling) {
        rootNode->firstChild = rootNode->firstChild->previousSibling;
    }
1480
1481
1482
1483
1484
1485
1486

1487
1488
1489
1490

1491
1492
1493
1494
1495
1496
1497

    memset(doc, 0, sizeof(domDocument));  
    doc->nodeType         = DOCUMENT_NODE;
    doc->documentNumber   = ++TSDPTR(domUniqueDocNr);
    doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->baseURIs         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));

    doc->documentElement  = NULL;
    Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->unparsedEntities, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->baseURIs, TCL_ONE_WORD_KEYS);


    h = Tcl_CreateHashEntry( &TSDPTR(tagNames), "(rootNode)", &hnew);
    rootNode = (domNode*) domAlloc(sizeof(domNode));
    memset(rootNode, 0, sizeof(domNode));
    rootNode->nodeType      = ELEMENT_NODE;
    rootNode->nodeFlags     = 0;
    rootNode->namespace     = 0;







>




>







1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641

    memset(doc, 0, sizeof(domDocument));  
    doc->nodeType         = DOCUMENT_NODE;
    doc->documentNumber   = ++TSDPTR(domUniqueDocNr);
    doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->baseURIs         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->NSscopes         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->documentElement  = NULL;
    Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->unparsedEntities, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->baseURIs, TCL_ONE_WORD_KEYS);
    Tcl_InitHashTable (doc->NSscopes, TCL_ONE_WORD_KEYS);

    h = Tcl_CreateHashEntry( &TSDPTR(tagNames), "(rootNode)", &hnew);
    rootNode = (domNode*) domAlloc(sizeof(domNode));
    memset(rootNode, 0, sizeof(domNode));
    rootNode->nodeType      = ELEMENT_NODE;
    rootNode->nodeFlags     = 0;
    rootNode->namespace     = 0;
1507
1508
1509
1510
1511
1512
1513

1514

1515
1516
1517
1518
1519
1520


1521
1522



















1523
1524
1525



1526
1527
1528
1529

1530



1531
1532
1533
1534
1535
1536
1537

/*---------------------------------------------------------------------------
|   domCreateDocument
|
\--------------------------------------------------------------------------*/
domDocument *
domCreateDocument (

    char      *documentElementTagName

)
{
    Tcl_HashEntry *h;
    int            hnew;
    domNode       *node; 
    domDocument   *doc;


    GetTDomTSD();




















    doc = domCreateDoc ();

    h = Tcl_CreateHashEntry( &TSDPTR(tagNames), documentElementTagName, &hnew); 



    node = (domNode*) domAlloc(sizeof(domNode));
    memset(node, 0, sizeof(domNode));
    node->nodeType        = ELEMENT_NODE;
    node->nodeFlags       = 0;

    node->namespace       = 0;



    node->nodeNumber      = ++TSDPTR(domUniqueNodeNr);
    node->ownerDocument   = doc;
    node->nodeName        = (char *)&(h->key);
    doc->documentElement  = node;
    doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof(Tcl_HashTable));
    doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof(Tcl_HashTable));
    Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);







>
|
>






>
>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



>
>
>




>
|
>
>
>







1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711

/*---------------------------------------------------------------------------
|   domCreateDocument
|
\--------------------------------------------------------------------------*/
domDocument *
domCreateDocument (
    Tcl_Interp *interp,
    char       *documentElementTagName,
    char       *uri
)
{
    Tcl_HashEntry *h;
    int            hnew;
    domNode       *node; 
    domDocument   *doc;
    char           prefix[MAX_PREFIX_LEN], *localName;
    domNS         *ns = NULL;
    GetTDomTSD();

    if (uri) {
        domSplitQName (documentElementTagName, prefix, &localName);
        DBG(fprintf (stderr, "rootName: -->%s<--, prefix: -->%s<--, localName: -->%s<--\n", documentElementTagName, prefix, localName);)
        if (prefix[0] != '\0') {
            if (!domIsNCNAME (prefix)) {
                Tcl_SetObjResult (interp, Tcl_NewStringObj("invalid prefix name", -1));
                return NULL;
            }
        }
        if (!domIsNCNAME (localName)) {
            Tcl_SetObjResult (interp, Tcl_NewStringObj ("invalid local name", -1));
            return NULL;
        }
    } else {
        if (!domIsNAME (documentElementTagName)) {
            Tcl_SetObjResult (interp, Tcl_NewStringObj ("invalid root element name", -1));
            return NULL;
        }
    }
    doc = domCreateDoc ();

    h = Tcl_CreateHashEntry( &TSDPTR(tagNames), documentElementTagName, &hnew); 
    if (uri) {
        ns = domNewNamespace (doc, prefix, uri);
    }
    node = (domNode*) domAlloc(sizeof(domNode));
    memset(node, 0, sizeof(domNode));
    node->nodeType        = ELEMENT_NODE;
    node->nodeFlags       = 0;
    if (uri) {
        node->namespace   = ns->index;
    } else {
        node->namespace   = 0;
    }
    node->nodeNumber      = ++TSDPTR(domUniqueNodeNr);
    node->ownerDocument   = doc;
    node->nodeName        = (char *)&(h->key);
    doc->documentElement  = node;
    doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof(Tcl_HashTable));
    doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof(Tcl_HashTable));
    Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
    while (attr && strcmp(attr->nodeName, attributeName)) {
        attr = attr->nextSibling;
    }
    if (attr) {   
        if (attr->nodeFlags & IS_ID_ATTRIBUTE) {
            h = Tcl_FindHashEntry (node->ownerDocument->ids, attr->nodeValue);
            if (h) {
                tmp = Tcl_GetHashValue (h);
                Tcl_DeleteHashEntry (h);
                h = Tcl_CreateHashEntry (node->ownerDocument->ids, 
                                         attributeValue, &hnew);
                /* XXX what to do, if hnew = 0  ??? */
                Tcl_SetHashValue (h, tmp);
            }
        }







|







1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
    while (attr && strcmp(attr->nodeName, attributeName)) {
        attr = attr->nextSibling;
    }
    if (attr) {   
        if (attr->nodeFlags & IS_ID_ATTRIBUTE) {
            h = Tcl_FindHashEntry (node->ownerDocument->ids, attr->nodeValue);
            if (h) {
                tmp = (domNode *)Tcl_GetHashValue (h);
                Tcl_DeleteHashEntry (h);
                h = Tcl_CreateHashEntry (node->ownerDocument->ids, 
                                         attributeValue, &hnew);
                /* XXX what to do, if hnew = 0  ??? */
                Tcl_SetHashValue (h, tmp);
            }
        }
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225

3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244

3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263

3264
3265
3266

3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284

3285
3286
3287
3288
3289
3290
3291
}


EXTERN int tcldom_returnDocumentObj (Tcl_Interp *interp, domDocument *document,
                                 int setVariable, Tcl_Obj *var_name);

void
tdom_freeProc (interp, userData)
    Tcl_Interp *interp;
    void *userData;

{
    char         objCmdName[40];
    Tcl_CmdInfo  cmd_info;
    domReadInfo *info = (domReadInfo *) userData;
    
    sprintf (objCmdName, "domDoc%d", info->document->documentNumber);
    if (!Tcl_GetCommandInfo (interp, objCmdName, &cmd_info)) {
        domFreeDocument (info->document, NULL, NULL);
        if (info->activeNS) {
            Tcl_Free ( (char *) info->activeNS);
        }
    }
    Tcl_Free ( (char *) info);
}

void
tdom_resetProc (interp, userData)
    Tcl_Interp *interp;
    void *userData;

{
    char         objCmdName[40];
    Tcl_CmdInfo  cmd_info;
    domReadInfo *info = (domReadInfo *) userData;
    domDocument *doc;
    GetTDomTSD();

    sprintf (objCmdName, "domDoc%d", info->document->documentNumber);
    if (!Tcl_GetCommandInfo (interp, objCmdName, &cmd_info)) {
        domFreeDocument (info->document, NULL, NULL);
    } 

    doc = (domDocument *) Tcl_Alloc (sizeof (domDocument));
    memset(doc, 0, sizeof(domDocument));  
    doc->nodeType         = DOCUMENT_NODE;
    doc->documentNumber   = ++TSDPTR(domUniqueDocNr);
    doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->baseURIs         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));

    Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->unparsedEntities, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->baseURIs, TCL_ONE_WORD_KEYS);


    info->document          = doc;
    info->currentNode       = NULL;
    info->depth             = 0;
    info->ignoreWhiteSpaces = 1;
    info->encoding_8bit     = 0;
    info->storeLineColumn   = 0;
    info->feedbackAfter     = 0;
    info->lastFeedbackPosition = 0;
    info->interp            = interp;
    info->currentNSIndex    = 0;
    info->activeNSpos       = -1;
}

void
tdom_parserResetProc (parser, userData)
    XML_Parser parser;
    void *userData;

{
    domReadInfo *info = (domReadInfo *) userData;

    info->parser = parser;
}

int







|
|
|
>
















|
|
|
>



















>



>















|
|
|
>







3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
}


EXTERN int tcldom_returnDocumentObj (Tcl_Interp *interp, domDocument *document,
                                 int setVariable, Tcl_Obj *var_name);

void
tdom_freeProc (
    Tcl_Interp *interp,
    void       *userData
)
{
    char         objCmdName[40];
    Tcl_CmdInfo  cmd_info;
    domReadInfo *info = (domReadInfo *) userData;
    
    sprintf (objCmdName, "domDoc%d", info->document->documentNumber);
    if (!Tcl_GetCommandInfo (interp, objCmdName, &cmd_info)) {
        domFreeDocument (info->document, NULL, NULL);
        if (info->activeNS) {
            Tcl_Free ( (char *) info->activeNS);
        }
    }
    Tcl_Free ( (char *) info);
}

void
tdom_resetProc (
    Tcl_Interp *interp,
    void       *userData
)
{
    char         objCmdName[40];
    Tcl_CmdInfo  cmd_info;
    domReadInfo *info = (domReadInfo *) userData;
    domDocument *doc;
    GetTDomTSD();

    sprintf (objCmdName, "domDoc%d", info->document->documentNumber);
    if (!Tcl_GetCommandInfo (interp, objCmdName, &cmd_info)) {
        domFreeDocument (info->document, NULL, NULL);
    } 

    doc = (domDocument *) Tcl_Alloc (sizeof (domDocument));
    memset(doc, 0, sizeof(domDocument));  
    doc->nodeType         = DOCUMENT_NODE;
    doc->documentNumber   = ++TSDPTR(domUniqueDocNr);
    doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->baseURIs         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    doc->NSscopes         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
    Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->unparsedEntities, TCL_STRING_KEYS);
    Tcl_InitHashTable (doc->baseURIs, TCL_ONE_WORD_KEYS);
    Tcl_InitHashTable (doc->NSscopes, TCL_ONE_WORD_KEYS);

    info->document          = doc;
    info->currentNode       = NULL;
    info->depth             = 0;
    info->ignoreWhiteSpaces = 1;
    info->encoding_8bit     = 0;
    info->storeLineColumn   = 0;
    info->feedbackAfter     = 0;
    info->lastFeedbackPosition = 0;
    info->interp            = interp;
    info->currentNSIndex    = 0;
    info->activeNSpos       = -1;
}

void
tdom_parserResetProc (
    XML_Parser parser,
    void      *userData
)
{
    domReadInfo *info = (domReadInfo *) userData;

    info->parser = parser;
}

int
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324

3325
3326
3327
3328
3329
3330
3331
    domNode         *rootNode;
    domReadInfo     *info;
    domLineColumn   *lc;
    Tcl_HashEntry   *h;
    TclGenExpatInfo *expat;
    Tcl_Obj         *newObjName = NULL;
    TEncoding       *encoding;
    GetTDomTSD();


    static char *tdomMethods[] = {
        "enable", "getdoc",
        "setResultEncoding", "setStoreLineColumn",
        "setExternalEntityResolver", "keepEmpties",
        "remove",
        NULL
    };
    enum tdomMethod {
        m_enable, m_getdoc,
        m_setResultEncoding, m_setStoreLineColumn,
        m_setExternalEntityResolver, m_keepEmpties,
        m_remove,
    };

    
    if (objc < 3 || objc > 4) {
        Tcl_WrongNumArgs (interp, 1, objv, tdom_usage);
        return TCL_ERROR;
    }

    if (!CheckExpatParserObj (interp, objv[1])) {







<
<














>







3481
3482
3483
3484
3485
3486
3487


3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
    domNode         *rootNode;
    domReadInfo     *info;
    domLineColumn   *lc;
    Tcl_HashEntry   *h;
    TclGenExpatInfo *expat;
    Tcl_Obj         *newObjName = NULL;
    TEncoding       *encoding;



    static char *tdomMethods[] = {
        "enable", "getdoc",
        "setResultEncoding", "setStoreLineColumn",
        "setExternalEntityResolver", "keepEmpties",
        "remove",
        NULL
    };
    enum tdomMethod {
        m_enable, m_getdoc,
        m_setResultEncoding, m_setStoreLineColumn,
        m_setExternalEntityResolver, m_keepEmpties,
        m_remove,
    };
    GetTDomTSD();
    
    if (objc < 3 || objc > 4) {
        Tcl_WrongNumArgs (interp, 1, objv, tdom_usage);
        return TCL_ERROR;
    }

    if (!CheckExpatParserObj (interp, objv[1])) {
3362
3363
3364
3365
3366
3367
3368

3369
3370
3371

3372
3373
3374
3375
3376
3377
3378
        doc = (domDocument *) Tcl_Alloc (sizeof (domDocument));
        memset(doc, 0, sizeof(domDocument));  
        doc->nodeType         = DOCUMENT_NODE;
        doc->documentNumber   = ++TSDPTR(domUniqueDocNr);
        doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
        doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
        doc->baseURIs         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));

        Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);
        Tcl_InitHashTable (doc->unparsedEntities, TCL_STRING_KEYS);
        Tcl_InitHashTable (doc->baseURIs, TCL_ONE_WORD_KEYS);


        info = (domReadInfo *) Tcl_Alloc (sizeof (domReadInfo));
        info->document          = doc;
        info->currentNode       = NULL;
        info->depth             = 0;
        info->ignoreWhiteSpaces = 1;
        info->encoding_8bit     = 0;







>



>







3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
        doc = (domDocument *) Tcl_Alloc (sizeof (domDocument));
        memset(doc, 0, sizeof(domDocument));  
        doc->nodeType         = DOCUMENT_NODE;
        doc->documentNumber   = ++TSDPTR(domUniqueDocNr);
        doc->ids              = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
        doc->unparsedEntities = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
        doc->baseURIs         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
        doc->NSscopes         = (Tcl_HashTable *)Tcl_Alloc (sizeof (Tcl_HashTable));
        Tcl_InitHashTable (doc->ids, TCL_STRING_KEYS);
        Tcl_InitHashTable (doc->unparsedEntities, TCL_STRING_KEYS);
        Tcl_InitHashTable (doc->baseURIs, TCL_ONE_WORD_KEYS);
        Tcl_InitHashTable (doc->NSscopes, TCL_ONE_WORD_KEYS);

        info = (domReadInfo *) Tcl_Alloc (sizeof (domReadInfo));
        info->document          = doc;
        info->currentNode       = NULL;
        info->depth             = 0;
        info->ignoreWhiteSpaces = 1;
        info->encoding_8bit     = 0;
Changes to generic/dom.h.
25
26
27
28
29
30
31










32
33
34
35
36
37
38
39
40
|   Portions created by Jochen Loewer are Copyright (C) 1998, 1999
|   Jochen Loewer. All Rights Reserved.
|
|   Contributor(s):
|
|
|   $Log$










|   Revision 1.1  2002/02/22 01:05:35  rolf
|   Initial revision
|
|
|
|   written by Jochen Loewer
|   April 5, 1999
|
\--------------------------------------------------------------------------*/







>
>
>
>
>
>
>
>
>
>
|
|







25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|   Portions created by Jochen Loewer are Copyright (C) 1998, 1999
|   Jochen Loewer. All Rights Reserved.
|
|   Contributor(s):
|
|
|   $Log$
|   Revision 1.4  2002/03/10 01:14:57  rolf
|   Introduced distinction between XML Name and XML NC Name.
|
|   Revision 1.3  2002/03/07 22:09:46  rolf
|   Added infrastructur to be able to do NCNAME tests.
|   Freeze of actual state, befor feeding stuff to Jochen.
|
|   Revision 1.2  2002/02/24 02:31:27  rolf
|   Fixed UTF-8 char byte length determination
|
|   Revision 1.1.1.1  2002/02/22 01:05:35  rolf
|   tDOM0.7test with Jochens first set of patches
|
|
|
|   written by Jochen Loewer
|   April 5, 1999
|
\--------------------------------------------------------------------------*/
100
101
102
103
104
105
106




























































































































































































107
108
109
110
111
112
113

#if (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0) || TCL_MAJOR_VERSION < 8 
#define TclOnly8Bits 1
#else
#define TclOnly8Bits 0
#endif






























































































































































































/*--------------------------------------------------------------------------
|   DOMString
|
\-------------------------------------------------------------------------*/
typedef char* domString;   /* should 16-bit unicode character !!*/








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311

#if (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0) || TCL_MAJOR_VERSION < 8 
#define TclOnly8Bits 1
#else
#define TclOnly8Bits 0
#endif

#define UTF8_1BYTE_CHAR(c) ( 0    == ((c) & 0x80))
#define UTF8_2BYTE_CHAR(c) ( 0xC0 == ((c) & 0xE0))
#define UTF8_3BYTE_CHAR(c) ( 0xE0 == ((c) & 0xF0))
#define UTF8_4BYTE_CHAR(c) ( 0xF0 == ((c) & 0xF8))

#if TclOnly8Bits
#define UTF8_CHAR_LEN(c) 1
#else 
#define UTF8_CHAR_LEN(c) \
  UTF8_1BYTE_CHAR((c)) ? 1 : \
   (UTF8_2BYTE_CHAR((c)) ? 2 : \
     (UTF8_3BYTE_CHAR((c)) ? 3 : 0))
#endif

/* The following 2 defines are out of the expat code */

/* A 2 byte UTF-8 representation splits the characters 11 bits
between the bottom 5 and 6 bits of the bytes.
We need 8 bits to index into pages, 3 bits to add to that index and
5 bits to generate the mask. */
#define UTF8_GET_NAMING2(pages, byte) \
    (namingBitmap[((pages)[(((byte)[0]) >> 2) & 7] << 3) \
                      + ((((byte)[0]) & 3) << 1) \
                      + ((((byte)[1]) >> 5) & 1)] \
         & (1 << (((byte)[1]) & 0x1F)))

/* A 3 byte UTF-8 representation splits the characters 16 bits
between the bottom 4, 6 and 6 bits of the bytes.
We need 8 bits to index into pages, 3 bits to add to that index and
5 bits to generate the mask. */
#define UTF8_GET_NAMING3(pages, byte) \
  (namingBitmap[((pages)[((((byte)[0]) & 0xF) << 4) \
                             + ((((byte)[1]) >> 2) & 0xF)] \
                       << 3) \
                      + ((((byte)[1]) & 3) << 1) \
                      + ((((byte)[2]) >> 5) & 1)] \
         & (1 << (((byte)[2]) & 0x1F)))

#define UTF8_GET_NAMING_NMTOKEN(p, n) \
  ((n) == 1 \
  ? nameChar7Bit[(int)(*(p))] \
  : ((n) == 2 \
    ? UTF8_GET_NAMING2(nmstrtPages, (const unsigned char *)(p)) \
    : ((n) == 3 \
      ? UTF8_GET_NAMING3(nmstrtPages, (const unsigned char *)(p)) \
      : 0)))

#define UTF8_GET_NAMING_NCNMTOKEN(p, n) \
  ((n) == 1 \
  ? NCnameChar7Bit[(int)(*(p))] \
  : ((n) == 2 \
    ? UTF8_GET_NAMING2(nmstrtPages, (const unsigned char *)(p)) \
    : ((n) == 3 \
      ? UTF8_GET_NAMING3(nmstrtPages, (const unsigned char *)(p)) \
      : 0)))


#define UTF8_GET_NAMING_NAME(p, n) \
  ((n) == 1 \
  ? nameStart7Bit[(int)(*(p))] \
  : ((n) == 2 \
    ? UTF8_GET_NAMING2(namePages, (const unsigned char *)(p)) \
    : ((n) == 3 \
      ? UTF8_GET_NAMING3(namePages, (const unsigned char *)(p)) \
      : 0)))

#define UTF8_GET_NAMING_NCNAME(p, n) \
  ((n) == 1 \
  ? NCnameStart7Bit[(int)(*(p))] \
  : ((n) == 2 \
    ? UTF8_GET_NAMING2(namePages, (const unsigned char *)(p)) \
    : ((n) == 3 \
      ? UTF8_GET_NAMING3(namePages, (const unsigned char *)(p)) \
      : 0)))


#include "../expat-1.95.1/nametab.h"

static const unsigned char nameChar7Bit[] = {
/* 0x00 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x08 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x10 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x18 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x20 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x28 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00,
/* 0x30 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x38 */    0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x40 */    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x48 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x50 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x58 */    0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01,
/* 0x60 */    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x68 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x70 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x78 */    0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
};

static const unsigned char NCnameChar7Bit[] = {
/* 0x00 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x08 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x10 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x18 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x20 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x28 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00,
/* 0x30 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x38 */    0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x40 */    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x48 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x50 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x58 */    0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01,
/* 0x60 */    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x68 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x70 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x78 */    0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
};


static const unsigned char nameStart7Bit[] = {
/* 0x00 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x08 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x10 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x18 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x20 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x28 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x30 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x38 */    0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x40 */    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x48 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x50 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x58 */    0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01,
/* 0x60 */    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x68 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x70 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x78 */    0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
};


static const unsigned char NCnameStart7Bit[] = {
/* 0x00 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x08 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x10 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x18 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x20 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x28 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x30 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x38 */    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 0x40 */    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x48 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x50 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x58 */    0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01,
/* 0x60 */    0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x68 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x70 */    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
/* 0x78 */    0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
};


#if TclOnly8Bits == 1
#  define isNameStart(x) (isalpha(*x) || ((*x)=='_') || ((*x)==':'))
#  define isNameChar(x) (isalnum(*x)  || ((*x)=='_') || ((*x)=='-') || ((*x)=='.') || ((*x)==':'))
#  define isNCNameStart(x) (isalpha(*x) || ((*x)=='_'))
#  define isNCNameChar(x) (isalnum(*x)  || ((*x)=='_') || ((*x)=='-') || ((*x)=='.'))
#else 
static int isNameStart(char *c) 
{
    int clen;
    clen = UTF8_CHAR_LEN (*c);
    return (UTF8_GET_NAMING_NAME(c, clen));
}
static int isNCNameStart(char *c) 
{
    int clen;
    clen = UTF8_CHAR_LEN (*c);
    return (UTF8_GET_NAMING_NCNAME(c, clen));
}
static int isNameChar(char *c)
{
    int clen;
    clen = UTF8_CHAR_LEN (*c);
    return (UTF8_GET_NAMING_NMTOKEN(c, clen));
}
static int isNCNameChar(char *c)
{
    int clen;
    clen = UTF8_CHAR_LEN (*c);
    return (UTF8_GET_NAMING_NCNMTOKEN(c, clen));
}
#endif

/*--------------------------------------------------------------------------
|   DOMString
|
\-------------------------------------------------------------------------*/
typedef char* domString;   /* should 16-bit unicode character !!*/

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
typedef int domNodeFlags;

#define HAS_LINE_COLUMN           1     
#define VISIBLE_IN_TCL            2
#define IS_ID_ATTRIBUTE           4
#define HAS_BASEURI               8
#define DISABLE_OUTPUT_ESCAPING  16


typedef int domDocFlags;

#define OUTPUT_DEFAULT_XML        1
#define OUTPUT_DEFAULT_HTML       2
#define OUTPUT_DEFAULT_TEXT       4
#define OUTPUT_DEFAULT_UNKOWN     8







|







339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
typedef int domNodeFlags;

#define HAS_LINE_COLUMN           1     
#define VISIBLE_IN_TCL            2
#define IS_ID_ATTRIBUTE           4
#define HAS_BASEURI               8
#define DISABLE_OUTPUT_ESCAPING  16
#define HAS_NS_INFO              32

typedef int domDocFlags;

#define OUTPUT_DEFAULT_XML        1
#define OUTPUT_DEFAULT_HTML       2
#define OUTPUT_DEFAULT_TEXT       4
#define OUTPUT_DEFAULT_UNKOWN     8
199
200
201
202
203
204
205

206
207
208
209
210
211
212
    struct domNode   *fragments;
    int               nsCount;
    struct domNS     *namespaces;
    struct domNode   *rootNode;
    Tcl_HashTable    *ids;
    Tcl_HashTable    *unparsedEntities;
    Tcl_HashTable    *baseURIs;

    Tcl_Obj          *extResolver;
} domDocument;


/*--------------------------------------------------------------------------
|   namespace
|







>







397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
    struct domNode   *fragments;
    int               nsCount;
    struct domNS     *namespaces;
    struct domNode   *rootNode;
    Tcl_HashTable    *ids;
    Tcl_HashTable    *unparsedEntities;
    Tcl_HashTable    *baseURIs;
    Tcl_HashTable    *NSscopes;
    Tcl_Obj          *extResolver;
} domDocument;


/*--------------------------------------------------------------------------
|   namespace
|
342
343
344
345
346
347
348
349


350
351
352
353
354
355
356
|   Function prototypes
|
\-------------------------------------------------------------------------*/
char *         domException2String (domException expection);

void           domModuleInitialize (void);
domDocument *  domCreateDoc ();
domDocument *  domCreateDocument (char *documentElementTagName);


   
domDocument *  domReadDocument (XML_Parser parser, 
                                char *xml, 
                                int   length, 
                                int   ignoreWhiteSpaces,
                                TEncoding *encoding_8bit,
                                int   storeLineColumn,







|
>
>







541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
|   Function prototypes
|
\-------------------------------------------------------------------------*/
char *         domException2String (domException expection);

void           domModuleInitialize (void);
domDocument *  domCreateDoc ();
domDocument *  domCreateDocument (Tcl_Interp *interp,
                                  char *documentElementTagName,
                                  char *uri);
   
domDocument *  domReadDocument (XML_Parser parser, 
                                char *xml, 
                                int   length, 
                                int   ignoreWhiteSpaces,
                                TEncoding *encoding_8bit,
                                int   storeLineColumn,
Changes to generic/domalloc.c.
27
28
29
30
31
32
33



34
35
36
37
38
39
40
41
42
|   Jochen Loewer. All Rights Reserved.
|
|   Contributor(s):
|
|
|
|   $Log$



|   Revision 1.1  2002/02/22 01:05:35  rolf
|   Initial revision
|
|
|
|   written by Jochen Loewer
|   October, 2000
|
\--------------------------------------------------------------------------*/







>
>
>
|
|







27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|   Jochen Loewer. All Rights Reserved.
|
|   Contributor(s):
|
|
|
|   $Log$
|   Revision 1.2  2002/03/08 23:49:25  rolf
|   Fixed small, obvious bug in DBG code.
|
|   Revision 1.1.1.1  2002/02/22 01:05:35  rolf
|   tDOM0.7test with Jochens first set of patches
|
|
|
|   written by Jochen Loewer
|   October, 2000
|
\--------------------------------------------------------------------------*/
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
    domAllocBlock * hashedBlock;
    int             i, j, slots, bitmaps, blockSize;
    unsigned int    mask;
    char          * mem;
    unsigned int  * usedBitmap;
    
    
    DBG(fprintf(stderr, "\ndomAlloc %d ... %d \n", size, ++invokes);)

    if (size >= MAX_BINS) {
        fprintf(stderr, "\nSize too large as used for bin!\n");
        return NULL;
    }
    TDomThreaded( 
        Tcl_MutexLock (&binMutex);







|







211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    domAllocBlock * hashedBlock;
    int             i, j, slots, bitmaps, blockSize;
    unsigned int    mask;
    char          * mem;
    unsigned int  * usedBitmap;
    
    
    DBG(fprintf(stderr, "\ndomAlloc %d \n", size);)

    if (size >= MAX_BINS) {
        fprintf(stderr, "\nSize too large as used for bin!\n");
        return NULL;
    }
    TDomThreaded( 
        Tcl_MutexLock (&binMutex);
Changes to generic/domxpath.c.
34
35
36
37
38
39
40








41
42
43
44
45
46
47
48
49
|
|       Aug00    Rolf Ade   Rewrite of comparisons plus several
|                           bug fixes/reports
|
|       Aug01    Rolf Ade   id(), unparsed-entity(), lang(), fixes
|
|   $Log$








|   Revision 1.1  2002/02/22 01:05:35  rolf
|   Initial revision
|
|
|
|   written by Jochen Loewer
|   July, 1999
|
\---------------------------------------------------------------------------*/







>
>
>
>
>
>
>
>
|
|







34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
|       Aug00    Rolf Ade   Rewrite of comparisons plus several
|                           bug fixes/reports
|
|       Aug01    Rolf Ade   id(), unparsed-entity(), lang(), fixes
|
|   $Log$
|   Revision 1.3  2002/03/07 22:16:21  rolf
|   Improved recognition of REALs (of the form .123). Made variable name
|   recognition UTF-8 save.
|   Freeze of actual state, befor feeding stuff to Jochen.
|
|   Revision 1.2  2002/02/23 01:13:33  rolf
|   Some code tweaking for a mostly warning free MS build
|
|   Revision 1.1.1.1  2002/02/22 01:05:35  rolf
|   tDOM0.7test with Jochens first set of patches
|
|
|
|   written by Jochen Loewer
|   July, 1999
|
\---------------------------------------------------------------------------*/
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
                          **errMsg = '\0';                     \
                          strcpy(*errMsg, __func);             \
                          strcat(*errMsg, ": Expected " #msg); \
                          return NULL;

#define CHECK_RC          if (rc) return rc



/*----------------------------------------------------------------------------
|   Types for Lexer
|
\---------------------------------------------------------------------------*/
typedef enum {
    LPAR, RPAR, LBRACKET, RBRACKET, DOT, DOTDOT, ATTRIBUTE,
    COMMA,  COLONCOLON, LITERAL, NSPREFIX, NSWC, INTNUMBER, REALNUMBER,







<
<







140
141
142
143
144
145
146


147
148
149
150
151
152
153
                          **errMsg = '\0';                     \
                          strcpy(*errMsg, __func);             \
                          strcat(*errMsg, ": Expected " #msg); \
                          return NULL;

#define CHECK_RC          if (rc) return rc



/*----------------------------------------------------------------------------
|   Types for Lexer
|
\---------------------------------------------------------------------------*/
typedef enum {
    LPAR, RPAR, LBRACKET, RBRACKET, DOT, DOTDOT, ATTRIBUTE,
    COMMA,  COLONCOLON, LITERAL, NSPREFIX, NSWC, INTNUMBER, REALNUMBER,
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212


213
214
215
216
217
218
219
    "AxisAncestor", "AxisAncestorOrSelf", "AxisAttribute", "AxisChild",
    "AxisDescendant", "AxisDescendantOrSelf", "AxisFollowing",
    "AxisFollowingSibling", "AxisNamespace", "AxisParent",
    "AxisPreceding", "AxisPrecedingSilbing", "AxisSelf",
    "GetContextNode", "GetParentNode",
    
    "CombinePath", "IsRoot", "ToParent", "ToAncestors", "FillNodeList",
     "FillWithCurrentNode",
    "ExecIdKey"
};




/*----------------------------------------------------------------------------
|   Prototypes / Forwards
|
\---------------------------------------------------------------------------*/
DeclProduction(OrExpr);
DeclProduction(Predicate);
DeclProduction(RelativeLocationPath);
DeclProduction(AbsoluteLocationPath);

char *xpathFuncString (xpathResultSet  *rs );





/*----------------------------------------------------------------------------
|   xpath result set functions
|
\---------------------------------------------------------------------------*/
void xpathRSInit ( xpathResultSet *rs ) {








|

















|
>
>







193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    "AxisAncestor", "AxisAncestorOrSelf", "AxisAttribute", "AxisChild",
    "AxisDescendant", "AxisDescendantOrSelf", "AxisFollowing",
    "AxisFollowingSibling", "AxisNamespace", "AxisParent",
    "AxisPreceding", "AxisPrecedingSilbing", "AxisSelf",
    "GetContextNode", "GetParentNode",
    
    "CombinePath", "IsRoot", "ToParent", "ToAncestors", "FillNodeList",
    "FillWithCurrentNode",
    "ExecIdKey"
};




/*----------------------------------------------------------------------------
|   Prototypes / Forwards
|
\---------------------------------------------------------------------------*/
DeclProduction(OrExpr);
DeclProduction(Predicate);
DeclProduction(RelativeLocationPath);
DeclProduction(AbsoluteLocationPath);

char *xpathFuncString (xpathResultSet  *rs );

#ifndef isnan
int isnan(double number) { return (!(number == number)); }
#endif

/*----------------------------------------------------------------------------
|   xpath result set functions
|
\---------------------------------------------------------------------------*/
void xpathRSInit ( xpathResultSet *rs ) {

678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
            case '\t': i++; continue;

            case '(':  token = LPAR;     break;
            case ')':  token = RPAR;     break;
            case '[':  token = LBRACKET; break;
            case ']':  token = RBRACKET; break;

            case '.':  if (xpath[i+1] == '.') {
                           token = DOTDOT;
                           i++;
                       } else {
                           token = DOT;
                       }; break;

            case '@':  i++;
                       if ( (isalpha(xpath[i])) || (xpath[i]== '_') ) {
                           ps = &(xpath[i++]);
                           while (xpath[i] &&
                                  (isalnum(xpath[i]) ||
                                   (xpath[i]== '_')  ||
                                   (xpath[i]== '-')  ||







<
<
<
<
<
<
<







686
687
688
689
690
691
692







693
694
695
696
697
698
699
            case '\t': i++; continue;

            case '(':  token = LPAR;     break;
            case ')':  token = RPAR;     break;
            case '[':  token = LBRACKET; break;
            case ']':  token = RBRACKET; break;








            case '@':  i++;
                       if ( (isalpha(xpath[i])) || (xpath[i]== '_') ) {
                           ps = &(xpath[i++]);
                           while (xpath[i] &&
                                  (isalnum(xpath[i]) ||
                                   (xpath[i]== '_')  ||
                                   (xpath[i]== '-')  ||
785
786
787
788
789
790
791
792
793

794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810











811
812
813
814
815
816
817
                          token = MULTIPLY;
                      } else {
                          token = WCARDNAME;
                          tokens[l].strvalue = (char*)strdup("*");
                      }; break;

            case '$':  i++;
                       if (isalpha(xpath[i]) || xpath[i] == '_') {
                           ps = &(xpath[i++]);

                           while (xpath[i] &&
                                  (isalnum(xpath[i]) ||
                                   (xpath[i]== '_')  ||
                                   (xpath[i]== '-')  ||
                                   (xpath[i]== '.')
                                  )
                                 ) i++;
                           save = xpath[i];
                           xpath[i] = '\0';
                           tokens[l].strvalue = (char*)strdup(ps);
                           xpath[i--] = save;
                           token = VARIABLE;
                       } else {
                           free(tokens);
                           *errMsg = (char*)strdup("Expected variable name");
                           return NULL;
                       } break;












            default:   if ( (isalpha(xpath[i])) || (xpath[i]== '_') ) {
                           ps = &(xpath[i++]);
                           while (xpath[i] &&
                                  (isalnum(xpath[i]) ||
                                   (xpath[i]== '_')  ||
                                   (xpath[i]== '-')  ||







|
|
>
|
|
<
<
<
<
<









|
>
>
>
>
>
>
>
>
>
>
>







786
787
788
789
790
791
792
793
794
795
796
797





798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
                          token = MULTIPLY;
                      } else {
                          token = WCARDNAME;
                          tokens[l].strvalue = (char*)strdup("*");
                      }; break;

            case '$':  i++;
                       if ( isNameStart (&xpath[i])) {
                           ps = &(xpath[i]);
                           i += UTF8_CHAR_LEN (xpath[i]);
                           while (xpath[i] && isNameChar(&xpath[i]))
                               i +=  UTF8_CHAR_LEN(xpath[i]);





                           save = xpath[i];
                           xpath[i] = '\0';
                           tokens[l].strvalue = (char*)strdup(ps);
                           xpath[i--] = save;
                           token = VARIABLE;
                       } else {
                           free(tokens);
                           *errMsg = (char*)strdup("Expected variable name");
                           return NULL;
                       }; break;

            case '.':  if (xpath[i+1] == '.') {
                           token = DOTDOT;
                           i++;
                           break;
                       } else if (!isdigit(xpath[i+1])) {
                           token = DOT;
                           break;
                       }
                       /* DOT followed by digit, ie a REAL.
                          Handled by default. Fall throu */

            default:   if ( (isalpha(xpath[i])) || (xpath[i]== '_') ) {
                           ps = &(xpath[i++]);
                           while (xpath[i] &&
                                  (isalnum(xpath[i]) ||
                                   (xpath[i]== '_')  ||
                                   (xpath[i]== '-')  ||
924
925
926
927
928
929
930
931
932


933


934
935
936
937
938
939
940
                               } else {
                                   token = WCARDNAME;
                                   tokens[l].strvalue = (char*)strdup(ps);
                               }
                               xpath[i] = save;
                           }
                           i--;
                       } else if (isdigit(xpath[i])) {
                           ps = &(xpath[i++]);


                           token = INTNUMBER;


                           while (xpath[i] && isdigit(xpath[i]))  i++;
                           if (xpath[i]=='.') {
                               token = REALNUMBER;
                               i++;
                               while (xpath[i] && isdigit(xpath[i]))  i++;
                           }
                           save = xpath[i];







|
|
>
>
|
>
>







932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
                               } else {
                                   token = WCARDNAME;
                                   tokens[l].strvalue = (char*)strdup(ps);
                               }
                               xpath[i] = save;
                           }
                           i--;
                       } else if (isdigit(xpath[i]) || (xpath[i] == '.')) {
                           if (xpath[i] == '.') {
                               token = REALNUMBER;
                           } else {
                               token = INTNUMBER;
                           }
                           ps = &(xpath[i++]);
                           while (xpath[i] && isdigit(xpath[i]))  i++;
                           if (xpath[i]=='.') {
                               token = REALNUMBER;
                               i++;
                               while (xpath[i] && isdigit(xpath[i]))  i++;
                           }
                           save = xpath[i];
1841
1842
1843
1844
1845
1846
1847


1848
1849
1850
1851
1852
1853
1854
            }
            return (strcmp( ((domAttrNode*)node)->nodeName, 
                            step->child->strvalue)==0);
        }
        return 0;
    } else
    if (step->child->type == IsFQElement) {


        contextNS = domLookupPrefix (exprContext, step->child->strvalue);
        if (!contextNS) return 0; /* Hmmm, that's more an error, than a not match */
        nodeUri = domNamespaceURI (node);
        if (!nodeUri) return 0;
        if (strcmp (contextNS->uri, nodeUri) != 0) return 0;
        if (node->nodeType == ELEMENT_NODE) {
            localName = domGetLocalName (node->nodeName);







>
>







1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
            }
            return (strcmp( ((domAttrNode*)node)->nodeName, 
                            step->child->strvalue)==0);
        }
        return 0;
    } else
    if (step->child->type == IsFQElement) {
        if (node->nodeType != ELEMENT_NODE && node->nodeType != ATTRIBUTE_NODE) 
            return 0;
        contextNS = domLookupPrefix (exprContext, step->child->strvalue);
        if (!contextNS) return 0; /* Hmmm, that's more an error, than a not match */
        nodeUri = domNamespaceURI (node);
        if (!nodeUri) return 0;
        if (strcmp (contextNS->uri, nodeUri) != 0) return 0;
        if (node->nodeType == ELEMENT_NODE) {
            localName = domGetLocalName (node->nodeName);
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
    xpathResultSet    *result,
    int               *docOrder,
    char             **errMsg
)
{
    xpathResultSet   leftResult, rightResult, replaceResult;
    xpathResultSet   pleftResult, prightResult, tResult;
    int              i, j, k, rc, res, pwhite, from, len,  NaN;
    char             *replaceStr, *pfrom, *pto, tmp[80], tmp1[80], *uri;
    domNode          *node, *child, *startingNode, *ancestor;
    domDocument      *doc;
    domAttrNode      *attr;
    double           leftReal;
    ast              nextStep;
    int              argc, savedDocOrder;
    xpathResultSets *args;
    xpathResultSet  *arg;
    Tcl_HashEntry   *entryPtr;
    unsigned int     leftNodeNr, rightNodeNr;
    int              left = 0, right = 0;
    double           dLeft = 0.0, dRight = 0.0;
    char             *leftStr = NULL, *rightStr = NULL;
#if TclOnly8Bits
    char             *fStr;
#else 
    int              found;







|










|







2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
    xpathResultSet    *result,
    int               *docOrder,
    char             **errMsg
)
{
    xpathResultSet   leftResult, rightResult, replaceResult;
    xpathResultSet   pleftResult, prightResult, tResult;
    int              i, j, k, rc, res, pwhite, len,  NaN;
    char             *replaceStr, *pfrom, *pto, tmp[80], tmp1[80], *uri;
    domNode          *node, *child, *startingNode, *ancestor;
    domDocument      *doc;
    domAttrNode      *attr;
    double           leftReal;
    ast              nextStep;
    int              argc, savedDocOrder;
    xpathResultSets *args;
    xpathResultSet  *arg;
    Tcl_HashEntry   *entryPtr;
    unsigned int     from, leftNodeNr, rightNodeNr;
    int              left = 0, right = 0;
    double           dLeft = 0.0, dRight = 0.0;
    char             *leftStr = NULL, *rightStr = NULL;
#if TclOnly8Bits
    char             *fStr;
#else 
    int              found;
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
        if (step->type == AxisDescendantOrSelf) {
            if (xpathNodeTest(ctxNode, exprContext, step)) 
                rsAddNode( result, ctxNode);
        }
        startingNode = ctxNode;
        node = ctxNode->firstChild;
        while (node && node != startingNode) {
           if (xpathNodeTest(node, exprContext, step)) rsAddNode( result, node);
           if ((node->nodeType == ELEMENT_NODE) && (node->firstChild)) {
               node = node->firstChild;
               continue;
           }
           if (node->nextSibling) {
               node = node->nextSibling;
               continue;
           }
           while ( node->parentNode &&
                  (node->parentNode != startingNode) &&
                  (node->parentNode->nextSibling == NULL) ) {

               node = node->parentNode;
           }
           if ((node != startingNode) &&
               (node->parentNode)     &&
               (node->parentNode != startingNode)
           ) {
               node = node->parentNode->nextSibling;
           } else {
               break;
           }
        }
    } else

    if (step->type == AxisSelf) {
        *docOrder = 1;
        DBG(fprintf(stderr, "AxisSelf :: \n");)
        if (xpathNodeTest(ctxNode, exprContext, step)) {







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
        if (step->type == AxisDescendantOrSelf) {
            if (xpathNodeTest(ctxNode, exprContext, step)) 
                rsAddNode( result, ctxNode);
        }
        startingNode = ctxNode;
        node = ctxNode->firstChild;
        while (node && node != startingNode) {
            if (xpathNodeTest(node, exprContext, step)) rsAddNode( result, node);
            if ((node->nodeType == ELEMENT_NODE) && (node->firstChild)) {
                node = node->firstChild;
                continue;
            }
            if (node->nextSibling) {
                node = node->nextSibling;
                continue;
            }
            while ( node->parentNode &&
                    (node->parentNode != startingNode) &&
                    (node->parentNode->nextSibling == NULL) ) {
                
                node = node->parentNode;
            }
            if ((node != startingNode) &&
                (node->parentNode)     &&
                (node->parentNode != startingNode)
                ) {
                node = node->parentNode->nextSibling;
            } else {
                break;
            }
        }
    } else

    if (step->type == AxisSelf) {
        *docOrder = 1;
        DBG(fprintf(stderr, "AxisSelf :: \n");)
        if (xpathNodeTest(ctxNode, exprContext, step)) {
Changes to generic/domxslt.c.
32
33
34
35
36
37
38
39


40
41
42










43
44














45
46
47
48
49
50
51
|
|       Fall/Winter 01 Rolf Ade rewrite of xsl:number, xsl:key/key(),
|                               handling of toplevel var/parameter,
|                               plenty of fixes and enhancements all
|                               over the place.
|
|   $Log$
|   Revision 1.1  2002/02/22 01:05:35  rolf


|   Initial revision
|
|   Revision 1.5  2002/02/04 22:10:59  jolo










|   rolf 04022002
|














|
|
|   written by Jochen Loewer
|   June, 2000
|
\---------------------------------------------------------------------------*/








|
>
>
|

|
>
>
>
>
>
>
>
>
>
>
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>







32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
|       Fall/Winter 01 Rolf Ade rewrite of xsl:number, xsl:key/key(),
|                               handling of toplevel var/parameter,
|                               plenty of fixes and enhancements all
|                               over the place.
|
|   $Log$
|   Revision 1.6  2002/03/16 13:06:06  rolf
|   Optimised xsl:sort: the string or numeric value of the nodes to sort
|   are computed only once and cached for further comparisons in the sort
|   process.
|
|   Revision 1.5  2002/03/03 20:08:25  rolf
|   Improved detection of improper stylesheets: now triggers error if any
|   mandatory attribute of a xsl element is missing. The mandatory
|   attributes are: xsl:stylesheet: version; xsl:transform: version;
|   xsl:include: href; xsl:import: href; xsl:strip-space: elements;
|   xsl:preserve-space: elements; xsl:call-template: name;
|   xsl:namespace-alias: stylesheet-prefix result-prefix; xsl:element:
|   name; xsl:attribute: name; xsl:attribute-set: name;
|   xsl:processing-instruction: name; xsl:value-of: select; xsl:for-each:
|   select; xsl:if: test; xsl:when: test; xsl:variable: name; xsl:param:
|   name; xsl:copy-of: select; xsl:with-param: name; xsl:key: name match
|   use
|
|   Revision 1.4  2002/03/01 04:06:59  rolf
|   Improved detection of improper stylesheets: xsl:include xsl:import
|   xsl:strip-space xsl:preserve-space xsl:apply-imports
|   xsl:namespace-alias xsl:value-of xsl:number xsl:sort xsl:copy-of
|   xsl:key xsl:decimal-format and xsl:output must be emtpy.
|
|   Revision 1.3  2002/02/24 02:31:27  rolf
|   Fixed UTF-8 char byte length determination
|
|   Revision 1.2  2002/02/23 01:13:33  rolf
|   Some code tweaking for a mostly warning free MS build
|
|   Revision 1.1.1.1  2002/02/22 01:05:35  rolf
|   tDOM0.7test with Jochens first set of patches
|
|
|   written by Jochen Loewer
|   June, 2000
|
\---------------------------------------------------------------------------*/

126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    a_count, a_dataType, a_disableOutputEscaping,
    a_doctypePublic, a_doctypeSystem, a_elements, a_encoding,
    a_format, a_from, a_href, a_lang, a_level, a_match, a_mediaType, a_method,
    a_mode, a_name, a_namespace, a_order, a_prio, a_select, a_space,
    a_terminate, a_test, a_use, a_useAttributeSets, a_value, 
    a_groupingSeparator, a_groupingSize,    
    a_decimalSeparator, a_infinity, a_minusSign, a_nan, a_percent, 
    a_perMille, a_zeroDigit, a_digit, a_patternSeparator

} xsltAttr;



/*--------------------------------------------------------------------------
|   xsltTemplate







|







152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    a_count, a_dataType, a_disableOutputEscaping,
    a_doctypePublic, a_doctypeSystem, a_elements, a_encoding,
    a_format, a_from, a_href, a_lang, a_level, a_match, a_mediaType, a_method,
    a_mode, a_name, a_namespace, a_order, a_prio, a_select, a_space,
    a_terminate, a_test, a_use, a_useAttributeSets, a_value, 
    a_groupingSeparator, a_groupingSize,    
    a_decimalSeparator, a_infinity, a_minusSign, a_nan, a_percent, 
    a_perMille, a_zeroDigit, a_digit, a_patternSeparator, a_version

} xsltAttr;



/*--------------------------------------------------------------------------
|   xsltTemplate
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
                        domNode *actionNode,  char **errMsg);

static domDocument * getExternalDocument (Tcl_Interp *interp, xsltState *xs,
                                          domDocument *xsltDoc, char *baseURI,
                                          char *href, char **errMsg);


/*----------------------------------------------------------------------------
|   UtfCount     
|
\---------------------------------------------------------------------------*/
static int
UtfCount(
    int ch
)
{
    if ((ch > 0) && (ch < 0x80)) { return 1; }
    if (ch <= 0x7FF)             { return 2; }
    if (ch <= 0xFFFF)            { return 3; } 
    return 0;
}

/*----------------------------------------------------------------------------
|   printXML
|
\---------------------------------------------------------------------------*/
static void printXML (domNode *node, int level, int maxlevel) {

    domTextNode *tnode;







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







413
414
415
416
417
418
419















420
421
422
423
424
425
426
                        domNode *actionNode,  char **errMsg);

static domDocument * getExternalDocument (Tcl_Interp *interp, xsltState *xs,
                                          domDocument *xsltDoc, char *baseURI,
                                          char *href, char **errMsg);

















/*----------------------------------------------------------------------------
|   printXML
|
\---------------------------------------------------------------------------*/
static void printXML (domNode *node, int level, int maxlevel) {

    domTextNode *tnode;
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
            Tcl_Alloc (sizeof (xsltNumberFormatToken) * 20);
        memset (format->tokens, 0, sizeof (xsltNumberFormatToken) * 20);
        format->maxtokens = 20;
        Tcl_SetHashValue (h, format);
        format->formatStr = p = Tcl_GetHashKey (&(xs->formats), h);
    }
    while (*p) {
        clen = UtfCount (*p);
        if (!clen) {
            *errMsg = 
                strdup("xsl:number: UTF-8 form of character longer than 3 Byte");
            return NULL;
        }
        if (clen > 1) {
            /* hack: skip over multibyte chars - this may be wrong */







|







743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
            Tcl_Alloc (sizeof (xsltNumberFormatToken) * 20);
        memset (format->tokens, 0, sizeof (xsltNumberFormatToken) * 20);
        format->maxtokens = 20;
        Tcl_SetHashValue (h, format);
        format->formatStr = p = Tcl_GetHashKey (&(xs->formats), h);
    }
    while (*p) {
        clen = UTF8_CHAR_LEN(*p);
        if (!clen) {
            *errMsg = 
                strdup("xsl:number: UTF-8 form of character longer than 3 Byte");
            return NULL;
        }
        if (clen > 1) {
            /* hack: skip over multibyte chars - this may be wrong */
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775

#define addSeperator  \
    p++;                                         \
    if (*p) {                                    \
        format->tokens[nrOfTokens].sepStart = p; \
    }                                            \
    while (*p) {                                 \
        clen = UtfCount (*p);                    \
        if (!clen) {                             \
            *errMsg = strdup("xsl:number: UTF-8 form of character longer than 3 Byte"); \
            return NULL;                         \
        }                                        \
        if (clen > 1) {                          \
            /* hack: skip over multibyte chars - this may be wrong */ \
            format->tokens[nrOfTokens].sepLen += clen;  \







|







772
773
774
775
776
777
778
779
780
781
782
783
784
785
786

#define addSeperator  \
    p++;                                         \
    if (*p) {                                    \
        format->tokens[nrOfTokens].sepStart = p; \
    }                                            \
    while (*p) {                                 \
        clen = UTF8_CHAR_LEN(*p);                \
        if (!clen) {                             \
            *errMsg = strdup("xsl:number: UTF-8 form of character longer than 3 Byte"); \
            return NULL;                         \
        }                                        \
        if (clen > 1) {                          \
            /* hack: skip over multibyte chars - this may be wrong */ \
            format->tokens[nrOfTokens].sepLen += clen;  \
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
            stripPrecedence = xs->stripInfo.wildcardPrec;
        }
        nsname = domNamespaceURI (node);
        if (nsname) {
            h = Tcl_FindHashEntry (&(xs->stripInfo.NSWildcards), nsname);
            if (h) {
                strip = 1;
                f = Tcl_GetHashValue (h);
                if (*f >= stripPrecedence) {
                    stripPrecedence = *f;
                    stripPrio = -0.25;
                }
            }
            domSplitQName (node->nodeName, prefix, &localName);
            Tcl_DStringInit (&dStr);
            Tcl_DStringAppend (&dStr, nsname, -1);
            Tcl_DStringAppend (&dStr, localName, -1);
            h = Tcl_FindHashEntry (&(xs->stripInfo.FQNames),
                                   Tcl_DStringValue (&dStr));
            if (h) {
                strip = 1;
                f = Tcl_GetHashValue (h);
                if (*f >= stripPrecedence) {
                    stripPrecedence = *f;
                    stripPrio = 0.0;
                }
            }
        } else {
            h = Tcl_FindHashEntry (&(xs->stripInfo.NCNames), node->nodeName);
            if (h) {
                strip = 1;
                f = Tcl_GetHashValue (h);
                if (*f >= stripPrecedence) {
                    stripPrecedence = *f;
                    stripPrio = 0.0;
                }
            }
        }
        if (strip && xs->preserveInfo.hasData) {
            if (xs->preserveInfo.wildcardPrec > stripPrecedence) {
                strip = 0;
            } else {
                if (nsname) {
                    h = Tcl_FindHashEntry (&(xs->preserveInfo.FQNames),
                                           Tcl_DStringValue (&dStr));
                    if (h) {
                        f = Tcl_GetHashValue (h);
                        if (*f > stripPrecedence) {
                            strip = 0;
                        } else
                        if (*f == stripPrecedence && stripPrio < 0.0) {
                            strip = 0;
                        }
                    }
                    if (strip) {
                        h = Tcl_FindHashEntry (&(xs->preserveInfo.NSWildcards),
                                               nsname);
                        if (h) {
                            f = Tcl_GetHashValue (h);
                            if (*f > stripPrecedence) {
                                strip = 0;
                            } else 
                            if (*f == stripPrecedence && stripPrio < -0.25) {
                                strip = 0;
                            }
                        }
                    }
                } else {
                    h = Tcl_FindHashEntry (&(xs->preserveInfo.NCNames),
                                           node->nodeName);
                    if (h) {
                        f = Tcl_GetHashValue (h);
                        if (*f > stripPrecedence) {
                            strip = 0;
                        } else 
                        if (*f == stripPrecedence && stripPrio < 0.0) {
                            strip = 0;
                        }
                    }







|













|









|














|











|












|







1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
            stripPrecedence = xs->stripInfo.wildcardPrec;
        }
        nsname = domNamespaceURI (node);
        if (nsname) {
            h = Tcl_FindHashEntry (&(xs->stripInfo.NSWildcards), nsname);
            if (h) {
                strip = 1;
                f = (double *)Tcl_GetHashValue (h);
                if (*f >= stripPrecedence) {
                    stripPrecedence = *f;
                    stripPrio = -0.25;
                }
            }
            domSplitQName (node->nodeName, prefix, &localName);
            Tcl_DStringInit (&dStr);
            Tcl_DStringAppend (&dStr, nsname, -1);
            Tcl_DStringAppend (&dStr, localName, -1);
            h = Tcl_FindHashEntry (&(xs->stripInfo.FQNames),
                                   Tcl_DStringValue (&dStr));
            if (h) {
                strip = 1;
                f = (double *)Tcl_GetHashValue (h);
                if (*f >= stripPrecedence) {
                    stripPrecedence = *f;
                    stripPrio = 0.0;
                }
            }
        } else {
            h = Tcl_FindHashEntry (&(xs->stripInfo.NCNames), node->nodeName);
            if (h) {
                strip = 1;
                f = (double *)Tcl_GetHashValue (h);
                if (*f >= stripPrecedence) {
                    stripPrecedence = *f;
                    stripPrio = 0.0;
                }
            }
        }
        if (strip && xs->preserveInfo.hasData) {
            if (xs->preserveInfo.wildcardPrec > stripPrecedence) {
                strip = 0;
            } else {
                if (nsname) {
                    h = Tcl_FindHashEntry (&(xs->preserveInfo.FQNames),
                                           Tcl_DStringValue (&dStr));
                    if (h) {
                        f = (double *)Tcl_GetHashValue (h);
                        if (*f > stripPrecedence) {
                            strip = 0;
                        } else
                        if (*f == stripPrecedence && stripPrio < 0.0) {
                            strip = 0;
                        }
                    }
                    if (strip) {
                        h = Tcl_FindHashEntry (&(xs->preserveInfo.NSWildcards),
                                               nsname);
                        if (h) {
                            f = (double *)Tcl_GetHashValue (h);
                            if (*f > stripPrecedence) {
                                strip = 0;
                            } else 
                            if (*f == stripPrecedence && stripPrio < -0.25) {
                                strip = 0;
                            }
                        }
                    }
                } else {
                    h = Tcl_FindHashEntry (&(xs->preserveInfo.NCNames),
                                           node->nodeName);
                    if (h) {
                        f = (double *)Tcl_GetHashValue (h);
                        if (*f > stripPrecedence) {
                            strip = 0;
                        } else 
                        if (*f == stripPrecedence && stripPrio < 0.0) {
                            strip = 0;
                        }
                    }
1876
1877
1878
1879
1880
1881
1882






















































































1883
1884
1885
1886
1887
1888
1889
    }
    
    xpathRSFree( &inA ); xpathRSFree( &rsA );
    xpathRSFree( &inB ); xpathRSFree( &rsB );
    return 0;
}
























































































/*----------------------------------------------------------------------------
|   sortNodeSetFastMerge  -   use FastMergeSort of fast sorting
|
\---------------------------------------------------------------------------*/
static int fastMergeSort (
    xsltState * xs,







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
    }
    
    xpathRSFree( &inA ); xpathRSFree( &rsA );
    xpathRSFree( &inB ); xpathRSFree( &rsB );
    return 0;
}

static int myNodeGreater (
    int         typeText,
    int         asc,
    int         upperFirst,
    char      * strA,
    char      * strB,
    double      realA,
    double      realB,
    int       * greater
)
{
    int             rc;
#if TclOnly8Bits == 0
    char           *strAptr, *strBptr;
    int             lenA, lenB, len;
    Tcl_UniChar     unicharA, unicharB;
#endif

    *greater = 0;

    if (typeText) {

#if TclOnly8Bits
        /* TODO: this only works for 7 bit ASCII */
        rc = STRCASECMP(strA, strB);
        if (rc == 0) {
            rc = strcmp (strA, strB);
            if (!upperFirst) {
                rc *= -1;
            }
        }
DBG(   fprintf(stderr, "nodeGreater %d <-- strA='%s' strB='%s'\n", rc, strA, strB);)
#else    
        lenA = Tcl_NumUtfChars (strA, -1);
        lenB = Tcl_NumUtfChars (strB, -1);
        len = (lenA < lenB ? lenA : lenB);
        rc = Tcl_UtfNcasecmp (strA, strB, len);
        if (rc == 0) {
            if (lenA > lenB) {
                rc = 1;
            } else if (lenA < lenB) {
                rc = -1;
            }
        }
        if (rc == 0) {
            strAptr = strA;
            strBptr = strB;
            while (len-- > 0) {
                strAptr += Tcl_UtfToUniChar(strAptr, &unicharA);
                strBptr += Tcl_UtfToUniChar(strBptr, &unicharB);
                if (unicharA != unicharB) {
                    rc = unicharA - unicharB;
                    break;
                }
            }
            if (!upperFirst) {
                rc *= -1;
            }
        }
#endif
        if (asc) *greater = (rc > 0);
            else *greater = (rc < 0);

    } else {
DBG(   fprintf(stderr, "nodeGreater  realA='%f' realB='%f'\n",realA, realB);)
        if (isnan (realA) || isnan (realB)) {
            if (asc) {
                if (isnan (realA) && !isnan (realB)) {
                    *greater = 0;
                } else {
                    if (isnan (realB) && !isnan (realA)) *greater = 1;
                }
            } else {
                if (isnan (realA) && !isnan(realB)) {
                    *greater = 1;
                } else {
                    if (isnan (realB) && !isnan(realA)) *greater = 0;
                }
            }
        } else {
            if (asc) *greater = (realA > realB); 
            else *greater = (realA < realB);        
        } 
    }
    return 0;
}

/*----------------------------------------------------------------------------
|   sortNodeSetFastMerge  -   use FastMergeSort of fast sorting
|
\---------------------------------------------------------------------------*/
static int fastMergeSort (
    xsltState * xs,
1996
1997
1998
1999
2000
2001
2002













































































































































2003
2004
2005
2006
2007
2008
2009
                       n, errMsg);
    CHECK_RC;
    free(posb);
    free(b);
    return 0;
}















































































































































/*----------------------------------------------------------------------------
|   xsltSetVar
|
\---------------------------------------------------------------------------*/
static int xsltSetVar (
    xsltState       * xs,







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
                       n, errMsg);
    CHECK_RC;
    free(posb);
    free(b);
    return 0;
}


static int myFastMergeSort (
    int         txt,
    int         asc,
    int         upperFirst,
    domNode   * a[],
    int       * posa,
    domNode   * b[],
    int       * posb,
    char     ** vs,
    double    * vd,
    char     ** vstmp,
    double    * vdtmp,
    int         size,
    char     ** errMsg
) {
    domNode *tmp;
    int tmpPos, lptr, rptr, middle, i, j, gt, rc;
    char    *tmpVs;
    double   tmpVd;
    
    if (size < 10) {
          /* use simple and fast insertion for small sizes ! */
        for (i = 1; i < size; i++) {
            tmp    = a    [i];
            tmpPos = posa [i];
            tmpVs  = vs   [i];
            tmpVd  = vd   [i];
            j = i; 
            if (j>0) {
                rc = myNodeGreater(txt, asc, upperFirst, vs[j-1], tmpVs,
                                   vd[j-1], tmpVd, &gt);
                CHECK_RC;
            }            
            while ( j > 0 && gt) {
                a   [j] = a   [j-1];
                posa[j] = posa[j-1];
                vs  [j] = vs  [j-1];
                vd  [j] = vd  [j-1];
                j--;
                if (j>0) {
                    rc = myNodeGreater(txt, asc, upperFirst, vs[j-1], tmpVs,
                                       vd[j-1], tmpVd, &gt);
                    CHECK_RC;
                }
            }
            a   [j] = tmp;
            posa[j] = tmpPos;
            vs  [j] = tmpVs;
            vd  [j] = tmpVd;
        }
        return 0;
    }
    middle = size/2;
 
    rc = myFastMergeSort(txt, asc, upperFirst, a, posa, b, posb, vs, vd,
                         vstmp, vdtmp, middle, errMsg);
    CHECK_RC;
    rc = myFastMergeSort(txt, asc, upperFirst, a+middle, posa+middle, b+middle,
                         posb+middle, vs+middle, vd+middle, vstmp+middle,
                         vdtmp+middle, size-middle, errMsg);
    CHECK_RC;
 
    lptr = 0;
    rptr = middle;
 
    for (i = 0; i < size; i++) {
        if (lptr == middle) {
            b    [i] = a   [rptr  ];
            posb [i] = posa[rptr  ];
            vstmp[i] = vs  [rptr  ];
            vdtmp[i] = vd  [rptr++];
        } else if (rptr < size) {
            rc = myNodeGreater(txt, asc, upperFirst, vs[lptr], vs[rptr],
                             vd[lptr], vd[rptr], &gt); 
            if (gt) {
                b    [i] = a   [rptr  ];
                posb [i] = posa[rptr  ];
                vstmp[i] = vs  [rptr  ];
                vdtmp[i] = vd  [rptr++];
            } else {
                b    [i] = a   [lptr  ];
                posb [i] = posa[lptr  ];
                vstmp[i] = vs  [lptr  ];
                vdtmp[i] = vd  [lptr++];
            }
        } else {
            b    [i] = a   [lptr  ];
            posb [i] = posa[lptr  ];
            vstmp[i] = vs  [lptr  ];
            vdtmp[i] = vd  [lptr++];
        } 
    } 
    memcpy(a,    b,     size*sizeof(domNode*));
    memcpy(posa, posb,  size*sizeof(int*));
    memcpy(vs,   vstmp, size*sizeof(char*));
    memcpy(vd,   vdtmp, size*sizeof(double));
    return 0;
}

static int mysortNodeSetFastMerge(
    xsltState * xs,
    int         txt,
    int         asc,
    int         upperFirst,
    domNode   * nodes[], 
    int         n,
    char     ** vs,
    double    * vd,
    int       * pos,
    char     ** errMsg
)
{
    domNode **b;
    int      *posb;
    char    **vstmp;
    double   *vdtmp;
    int       rc;

    b = (domNode **) malloc( n * sizeof(domNode *) );
    if (b == NULL) {
        perror("malloc in sortNodeSetMergeSort");
        exit(1);
    }
    posb = (int *) malloc( n * sizeof(int) );
    if (posb == NULL) {
        perror("malloc in sortNodeSetMergeSort");
        exit(1);
    }
    vstmp = (char **) malloc (sizeof (char *) * n);
    vdtmp = (double *)malloc (sizeof (double) * n);
    
    rc = myFastMergeSort(txt, asc, upperFirst, nodes, pos, b, posb, vs, vd, 
                         vstmp, vdtmp, n, errMsg);
    free (posb);
    free (b);
    free (vstmp);
    free (vdtmp);
    CHECK_RC;
    return 0;
}

/*----------------------------------------------------------------------------
|   xsltSetVar
|
\---------------------------------------------------------------------------*/
static int xsltSetVar (
    xsltState       * xs,
2142
2143
2144
2145
2146
2147
2148

2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
    int               rc, d; 
    char             *select;
    Tcl_HashEntry    *h;
    xsltTopLevelVar  *topLevelVar;
    xsltVarInProcess *varInProcess, thisVarInProcess;
    xpathResultSet    nodeList;
    domNode          *savedCurrentXSLTNode;

       
#if 0       
    TRACE1("xsltGetVar variableName='%s' \n", variableName);
#endif    
    
    frame = xs->varFrames;
    d = 0;
    while (frame) {
        var = frame->vars;
        while (var) {
            /*TRACE2("is it var %d:'%s' ? \n", d, var->name);*/







>
|
<

<







2380
2381
2382
2383
2384
2385
2386
2387
2388

2389

2390
2391
2392
2393
2394
2395
2396
    int               rc, d; 
    char             *select;
    Tcl_HashEntry    *h;
    xsltTopLevelVar  *topLevelVar;
    xsltVarInProcess *varInProcess, thisVarInProcess;
    xpathResultSet    nodeList;
    domNode          *savedCurrentXSLTNode;
    Tcl_DString       dErrMsg;
    

    TRACE1("xsltGetVar variableName='%s' \n", variableName);

    
    frame = xs->varFrames;
    d = 0;
    while (frame) {
        var = frame->vars;
        while (var) {
            /*TRACE2("is it var %d:'%s' ? \n", d, var->name);*/
2221
2222
2223
2224
2225
2226
2227

2228
2229
2230


2231
2232
2233
2234
2235
2236
2237
2238
2239
                exit(1);
            }
            xs->varsInProcess = varInProcess->next;
            xs->currentXSLTNode = savedCurrentXSLTNode;
            return XPATH_OK;
        }
    }

    *errMsg = strdup ("Undefined Variable requested.");
    return XPATH_EVAL_ERR;
        


/*      rsSetString(result, ""); */
/*      return XPATH_OK; */
}



/*----------------------------------------------------------------------------
|   xsltAddTemplate
|







>
|
<
|
>
>
|
|







2458
2459
2460
2461
2462
2463
2464
2465
2466

2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
                exit(1);
            }
            xs->varsInProcess = varInProcess->next;
            xs->currentXSLTNode = savedCurrentXSLTNode;
            return XPATH_OK;
        }
    }
    Tcl_DStringInit (&dErrMsg);
    Tcl_DStringAppend (&dErrMsg, "Variable \"", -1);

    Tcl_DStringAppend (&dErrMsg, variableName, -1);
    Tcl_DStringAppend (&dErrMsg, "\" has not been declared.", -1);
    reportError (xs->currentXSLTNode, Tcl_DStringValue (&dErrMsg), errMsg);
    Tcl_DStringFree (&dErrMsg);
    return XPATH_EVAL_ERR;
}



/*----------------------------------------------------------------------------
|   xsltAddTemplate
|
2464
2465
2466
2467
2468
2469
2470



2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496


2497

2498
2499
2500
2501
2502
2503
2504
2505
2506
2507




2508
2509

2510
2511
2512
2513
2514
2515
2516
                        rc = xsltSetVar(xs, 1, str, context, currentNode, currentPos, 
                                        select, NULL, 0, errMsg);
                    } else {
                        rc = xsltSetVar(xs, 1, str, context, currentNode, currentPos, 
                                        NULL, child->firstChild, 0, errMsg);
                    }
                    CHECK_RC;



                }
            }
        }
        child = child->nextSibling;
    }
    return 0;
}


/*----------------------------------------------------------------------------
|   doSortActions
|
\---------------------------------------------------------------------------*/
static int doSortActions (
    xsltState       * xs,
    xpathResultSet  * nodelist,
    domNode         * actionNode,
    xpathResultSet  * context,
    domNode         * currentNode,
    int               currentPos,
    int             * sorted,
    char           ** errMsg    
)
{
    domNode *child;
    char    *str, *evStr, *select, *lang;


    int      rc, typeText, ascending, upperFirst = 1, *pos, i;

    ast      t;
    
    *sorted = 0;

    child = actionNode->lastChild; /* do it backwards, so that multiple sort
                                      levels are correctly processed */
    while (child) {
        if (child->nodeType == ELEMENT_NODE) {
            TRACE1("doSortActions child '%s' \n", child->nodeName);
            if (getTag(child) == sort) {




                typeText  = 1;
                ascending = 1;

                select = getAttr(child, "select", a_select);
                if (!select) select = ".";
                xs->currentXSLTNode = child;
                str = getAttr(child, "data-type", a_dataType);
                if (str) {
                    rc = evalAttrTemplates (xs, context, currentNode,
                                            currentPos, str, &evStr, errMsg);







>
>
>




















<



|
|
>
>
|
>
|

<
<






>
>
>
>


>







2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732

2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743


2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
                        rc = xsltSetVar(xs, 1, str, context, currentNode, currentPos, 
                                        select, NULL, 0, errMsg);
                    } else {
                        rc = xsltSetVar(xs, 1, str, context, currentNode, currentPos, 
                                        NULL, child->firstChild, 0, errMsg);
                    }
                    CHECK_RC;
                } else {
                    reportError (child, "xsl:with-param: missing mandatory attribute \"name\".", errMsg);
                    return -1;
                }
            }
        }
        child = child->nextSibling;
    }
    return 0;
}


/*----------------------------------------------------------------------------
|   doSortActions
|
\---------------------------------------------------------------------------*/
static int doSortActions (
    xsltState       * xs,
    xpathResultSet  * nodelist,
    domNode         * actionNode,
    xpathResultSet  * context,
    domNode         * currentNode,
    int               currentPos,

    char           ** errMsg    
)
{
    domNode       *child;
    char          *str, *evStr, *select, *lang;
    char         **vs = NULL;
    double        *vd = NULL;
    int            rc = 0, typeText, ascending, upperFirst, *pos = NULL, i, NaN;
    xpathResultSet rs;
    ast            t;
    


    child = actionNode->lastChild; /* do it backwards, so that multiple sort
                                      levels are correctly processed */
    while (child) {
        if (child->nodeType == ELEMENT_NODE) {
            TRACE1("doSortActions child '%s' \n", child->nodeName);
            if (getTag(child) == sort) {
                if (child->firstChild) {
                    reportError (child, "xsl:sort has to be empty.", errMsg);
                    return -1;
                }
                typeText  = 1;
                ascending = 1;
                upperFirst = 1;
                select = getAttr(child, "select", a_select);
                if (!select) select = ".";
                xs->currentXSLTNode = child;
                str = getAttr(child, "data-type", a_dataType);
                if (str) {
                    rc = evalAttrTemplates (xs, context, currentNode,
                                            currentPos, str, &evStr, errMsg);
2537
2538
2539
2540
2541
2542
2543

2544
2545
2546
2547




















2548
2549
2550




2551
2552


2553



2554
2555
2556
2557
2558




2559
2560
2561
2562
2563
2564
2565
2566
                /* jcl: TODO */
                lang = getAttr(child, "lang", a_lang);
                
                TRACE4("sorting with '%s' typeText %d ascending %d nodeSetLen=%d\n", 
                       select, typeText, ascending, nodelist->nr_nodes);
                rc = xpathParse(select, errMsg, &t, 0);
                CHECK_RC;

                pos = (int*) malloc( sizeof(int) * nodelist->nr_nodes);
                for (i=0; i<nodelist->nr_nodes;i++) pos[i] = i;

                xs->currentXSLTNode = child;




















                rc = sortNodeSetFastMerge(xs, t, select, typeText, ascending,
                                          upperFirst, nodelist->nodes,
                                          nodelist->nr_nodes, pos, errMsg);




                free(pos);
                CHECK_RC;


                xpathFreeAst( t );                 



                *sorted = 1;
            }
        }
        child = child->previousSibling;
    }




    return 0;
}


/*----------------------------------------------------------------------------
|   xsltNumber
|
\---------------------------------------------------------------------------*/







>
|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
>
>
>
>
|
<
>
>
|
>
>
>
|




>
>
>
>
|







2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823

2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
                /* jcl: TODO */
                lang = getAttr(child, "lang", a_lang);
                
                TRACE4("sorting with '%s' typeText %d ascending %d nodeSetLen=%d\n", 
                       select, typeText, ascending, nodelist->nr_nodes);
                rc = xpathParse(select, errMsg, &t, 0);
                CHECK_RC;
                if (!pos) 
                    pos = (int*) malloc( sizeof(int) * nodelist->nr_nodes);
                for (i=0; i<nodelist->nr_nodes;i++) pos[i] = i;

                xs->currentXSLTNode = child;
                
                if (!vs) {
                    vs = (char **) malloc (sizeof (char *) * nodelist->nr_nodes);
                    for (i=0; i<nodelist->nr_nodes;i++) vs[i] = NULL;
                    vd = (double *)malloc (sizeof (double) * nodelist->nr_nodes);
                }
                for (i = 0; i < nodelist->nr_nodes; i++) {
                    xpathRSInit (&rs);
                    rc = evalXPath (xs, nodelist, nodelist->nodes[i], i,
                                    select, &rs, errMsg);
                    if (rc < 0) 
                        goto doSortActionCleanUp;
                    
                    if (typeText) {
                        vs[i] = xpathFuncString (&rs);
                    } else {
                        vd[i] = xpathFuncNumber (&rs, &NaN);
                    }
                    xpathRSFree (&rs);
                }
                rc = mysortNodeSetFastMerge (xs, typeText, ascending,
                                             upperFirst, nodelist->nodes,
                                             nodelist->nr_nodes, vs, vd,
                                             pos, errMsg);
/*                  rc = sortNodeSetFastMerge(xs, t, select, typeText, ascending, */
/*                                            upperFirst, nodelist->nodes, */
/*                                            nodelist->nr_nodes, pos, errMsg); */
/*                  free(pos); */

                if (typeText) {
                    for (i = 0; i < nodelist->nr_nodes; i++) {
                        free (vs[i]);
                    }
                }
                if (rc < 0)
                    goto doSortActionCleanUp;
            }
        }
        child = child->previousSibling;
    }
 doSortActionCleanUp:
    if (pos) free (pos);
    if (vs) free (vs);
    if (vd) free (vd);
    return rc;
}


/*----------------------------------------------------------------------------
|   xsltNumber
|
\---------------------------------------------------------------------------*/
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
    domNS          *NS;
    Tcl_DString     dStr;
    domProcessingInstructionNode *pi;      
    xpathResultSet  rs, nodeList;
    char           *str, *str2, *mode, *select, *pc;
    char           *nsAT, *ns;
    char           *uri, *localName, prefix[MAX_PREFIX_LEN];
    int             rc, b, i, len, sorted, disableEsc = 0;
    double          currentPrio, currentPrec;

    if (actionNode->nodeType == TEXT_NODE) {
        domAppendNewTextNode(xs->lastNode, 
                             ((domTextNode*)actionNode)->nodeValue,
                             ((domTextNode*)actionNode)->valueLength,
                             TEXT_NODE, 0);







|







3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
    domNS          *NS;
    Tcl_DString     dStr;
    domProcessingInstructionNode *pi;      
    xpathResultSet  rs, nodeList;
    char           *str, *str2, *mode, *select, *pc;
    char           *nsAT, *ns;
    char           *uri, *localName, prefix[MAX_PREFIX_LEN];
    int             rc, b, i, len, disableEsc = 0;
    double          currentPrio, currentPrec;

    if (actionNode->nodeType == TEXT_NODE) {
        domAppendNewTextNode(xs->lastNode, 
                             ((domTextNode*)actionNode)->nodeValue,
                             ((domTextNode*)actionNode)->valueLength,
                             TEXT_NODE, 0);
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
                xpathRSFree( &nodeList ); 
                CHECK_RC;
                TRACE1("applyTemplates: evalXPath for select = '%s' gave back:\n", select);
                DBG(rsPrint(&rs));
            }
            
            rc = doSortActions (xs, &rs, actionNode, context, currentNode,
                                currentPos, &sorted, errMsg);
            CHECK_RC;
            /* should not be necessary, because every node set is
               returned already in doc Order */
            /*  if (!sorted) sortByDocOrder(&rs); */
            
            TRACE1("                evalXPath for select = '%s': (SORTED)\n", select);
            DBG(rsPrint(&rs));







|







3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
                xpathRSFree( &nodeList ); 
                CHECK_RC;
                TRACE1("applyTemplates: evalXPath for select = '%s' gave back:\n", select);
                DBG(rsPrint(&rs));
            }
            
            rc = doSortActions (xs, &rs, actionNode, context, currentNode,
                                currentPos, errMsg);
            CHECK_RC;
            /* should not be necessary, because every node set is
               returned already in doc Order */
            /*  if (!sorted) sortByDocOrder(&rs); */
            
            TRACE1("                evalXPath for select = '%s': (SORTED)\n", select);
            DBG(rsPrint(&rs));
2997
2998
2999
3000
3001
3002
3003
3004




3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
                /* Adding an Attribute to an element after
                   children have been added to it is an error.
                   Ignore the attribute. */
                break;
            }
            nsAT = getAttr(actionNode, "namespace", a_namespace);
            str = getAttr(actionNode, "name", a_name);
            if (str) {                




                rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                        str, &str2, errMsg);
                CHECK_RC;
                ns = NULL;
                Tcl_DStringInit (&dStr);
                if (nsAT) {
                    rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                            nsAT, &ns, errMsg);
                    CHECK_RC;
                    NS = domLookupURI (actionNode, ns);
                    if (NS) {
                        Tcl_DStringAppend (&dStr, NS->prefix, -1);
                        Tcl_DStringAppend (&dStr, ":", 1);
                        Tcl_DStringAppend (&dStr, str2, -1);
                    } else goto ignoreAttribute;
                } else {
                    domSplitQName (str2, prefix, &localName);
                    if (prefix[0] != '\0') {
                        if (strcmp (prefix, "xmlns")==0) goto ignoreAttribute;
                        NS = domLookupPrefix (actionNode, prefix);
                        if (NS) ns = NS->uri;
                        else goto ignoreAttribute;
                    } else {
                        if (strcmp (str2, "xmlns")==0) goto ignoreAttribute;
                    }
                    Tcl_DStringAppend (&dStr, str2, -1);
                }
                
                savedLastNode = xs->lastNode;
                xs->lastNode  = domNewElementNode (xs->resultDoc,  
                                    "container", ELEMENT_NODE);
                rc = ExecActions(xs, context, currentNode, currentPos,
                                 actionNode->firstChild, errMsg);
                CHECK_RC;
                pc = xpathGetTextValue (xs->lastNode, &len);
                domSetAttributeNS (savedLastNode, Tcl_DStringValue (&dStr), pc, ns);
                free(pc);
                Tcl_DStringFree (&dStr);
                domDeleteNode (xs->lastNode, NULL, NULL);
                xs->lastNode = savedLastNode;
            ignoreAttribute:
                free(str2);
            }
            break;
            
        case attributeSet: return 0;
            
        case callTemplate:
            tplChoosen = NULL;
            currentPrec = INT_MIN;







|
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
<







3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330

3331
3332
3333
3334
3335
3336
3337
                /* Adding an Attribute to an element after
                   children have been added to it is an error.
                   Ignore the attribute. */
                break;
            }
            nsAT = getAttr(actionNode, "namespace", a_namespace);
            str = getAttr(actionNode, "name", a_name);
            if (!str) {
                reportError (actionNode, "xsl:attribute: missing mandatory attribute \"name\".", errMsg);
                return -1;
            }
            
            rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                    str, &str2, errMsg);
            CHECK_RC;
            ns = NULL;
            Tcl_DStringInit (&dStr);
            if (nsAT) {
                rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                        nsAT, &ns, errMsg);
                CHECK_RC;
                NS = domLookupURI (actionNode, ns);
                if (NS) {
                    Tcl_DStringAppend (&dStr, NS->prefix, -1);
                    Tcl_DStringAppend (&dStr, ":", 1);
                    Tcl_DStringAppend (&dStr, str2, -1);
                } else goto ignoreAttribute;
            } else {
                domSplitQName (str2, prefix, &localName);
                if (prefix[0] != '\0') {
                    if (strcmp (prefix, "xmlns")==0) goto ignoreAttribute;
                    NS = domLookupPrefix (actionNode, prefix);
                    if (NS) ns = NS->uri;
                    else goto ignoreAttribute;
                } else {
                    if (strcmp (str2, "xmlns")==0) goto ignoreAttribute;
                }
                Tcl_DStringAppend (&dStr, str2, -1);
            }
                
            savedLastNode = xs->lastNode;
            xs->lastNode  = domNewElementNode (xs->resultDoc,  
                                               "container", ELEMENT_NODE);
            rc = ExecActions(xs, context, currentNode, currentPos,
                             actionNode->firstChild, errMsg);
            CHECK_RC;
            pc = xpathGetTextValue (xs->lastNode, &len);
            domSetAttributeNS (savedLastNode, Tcl_DStringValue (&dStr), pc, ns);
            free(pc);
            Tcl_DStringFree (&dStr);
            domDeleteNode (xs->lastNode, NULL, NULL);
            xs->lastNode = savedLastNode;
    ignoreAttribute:
            free(str2);

            break;
            
        case attributeSet: return 0;
            
        case callTemplate:
            tplChoosen = NULL;
            currentPrec = INT_MIN;
3109
3110
3111
3112
3113
3114
3115



3116
3117
3118
3119
3120
3121
3122
                                /* process the children as well */
                                rc = ExecActions(xs, context,
                                                 currentNode, currentPos,
                                                 child->firstChild, errMsg);
                                CHECK_RC;
                                return 0;
                            }                            



                        }
                        break;
                        
                    case otherwise:
                        /* process the children as well */
                        rc = ExecActions(xs, context, currentNode, currentPos,
                                         child->firstChild, errMsg);







>
>
>







3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
                                /* process the children as well */
                                rc = ExecActions(xs, context,
                                                 currentNode, currentPos,
                                                 child->firstChild, errMsg);
                                CHECK_RC;
                                return 0;
                            }                            
                        } else {
                            reportError (child, "xsl:when: missing mandatory attribute \"test\".", errMsg);
                            return -1;
                        }
                        break;
                        
                    case otherwise:
                        /* process the children as well */
                        rc = ExecActions(xs, context, currentNode, currentPos,
                                         child->firstChild, errMsg);
3239
3240
3241
3242
3243
3244
3245




3246
3247




3248
3249
3250
3251
3252
3253
3254
3255
3256










3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304




3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
                rc = ExecActions(xs, context, currentNode, currentPos,
                                 actionNode->firstChild, errMsg);
                CHECK_RC;
            }
            break;
            
        case copyOf:            




            select = getAttr(actionNode, "select", a_select);
            if (select != NULL) {




                xs->current = currentNode;
                rc = evalXPath(xs, context, currentNode, currentPos, select,
                               &rs, errMsg);
                CHECK_RC;            
                TRACE1(" copyOf select='%s':\n", select);
                DBG(rsPrint(&rs));
                if (rs.type == NodeSetResult) {
                    for (i=0; i<rs.nr_nodes; i++) { 
                        if (rs.nodes[i]->nodeType == DOCUMENT_NODE) {










                            child = rs.nodes[i]->firstChild;
                            while (child) {
                                n = domCloneNode(child, 1);
                                domAppendChild(xs->lastNode, n);
                                child = child->nextSibling;
                            }
                        } else {
                            if (*(rs.nodes[i]->nodeName) == '(' &&
                                ((strcmp(rs.nodes[i]->nodeName,"(fragment)")==0)
                                 || (strcmp(rs.nodes[i]->nodeName,"(rootNode)")==0))) {
                                child = rs.nodes[i]->firstChild;
                                while (child) {
                                    n = domCloneNode(child, 1);
                                    domAppendChild(xs->lastNode, n);
                                    child = child->nextSibling;
                                }
                            } else {
                                n = domCloneNode(rs.nodes[i], 1);
                                domAppendChild(xs->lastNode, n);
                            }
                        }
                    }
                } else
                if ((rs.type == AttrNodeSetResult) ||
                    (rs.type == AttrValueSetResult)) {
                    for (i=0; i<rs.nr_nodes; i++) { 
                        attr = (domAttrNode*)rs.nodes[i];
                        domSetAttribute(xs->lastNode, 
                                        attr->nodeName, attr->nodeValue);
                    }
                } 
                else {
                    str = xpathFuncString( &rs );
                    TRACE1("copyOf: xpathString='%s' \n", str);
                    domAppendNewTextNode(xs->lastNode, str, strlen(str),
                                         TEXT_NODE, 0);
                    free(str);
                }
                xpathRSFree( &rs );               
            }
            break;
            
        case decimalFormat: return 0;
        
        case element:
            nsAT = getAttr(actionNode, "namespace", a_namespace);
            str  = getAttr(actionNode, "name", a_name);
            if (str) {




                rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                        str, &str2, errMsg);
                CHECK_RC;
                
                ns = NULL;
                if (nsAT) {
                    rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                            nsAT, &ns, errMsg);
                    CHECK_RC;
                }
                savedLastNode = xs->lastNode;
                xs->lastNode = domAppendNewElementNode (xs->lastNode, str2, ns);
                free(str2);
                str = getAttr(actionNode, "use-attribute-sets", a_useAttributeSets);
                if (str) {
                    TRACE1("use-attribute-sets = '%s' \n", str);
                    rc = ExecUseAttributeSets (xs, context, currentNode, currentPos,
                                               str, errMsg);
                    CHECK_RC;
                }
                /* process the children as well */
                if (actionNode->firstChild) {
                    rc = ExecActions(xs, context, currentNode, currentPos,
                                     actionNode->firstChild, errMsg);
                }
                xs->lastNode = savedLastNode;
                CHECK_RC;
            }
            break;
            
        case fallback: return 0;
            
        case forEach:
            select = getAttr(actionNode, "select", a_select);
            if (!select) {







>
>
>
>

|
>
>
>
>
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>







<
<
<
<
<
<
<
<
<
<
|
|
|
|
|
|















|
<







|
>
>
>
>
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<







3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567










3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589

3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628

3629
3630
3631
3632
3633
3634
3635
                rc = ExecActions(xs, context, currentNode, currentPos,
                                 actionNode->firstChild, errMsg);
                CHECK_RC;
            }
            break;
            
        case copyOf:            
            if (actionNode->firstChild) {
                reportError (actionNode, "xsl:copy-of has to be empty.", errMsg);
                return -1;
            }
            select = getAttr(actionNode, "select", a_select);
            if (!select) {
                reportError (actionNode, "xsl:copy-of: missing mandatory attribute \"select\".", errMsg);
                return -1;
            }
            
            xs->current = currentNode;
            rc = evalXPath(xs, context, currentNode, currentPos, select,
                           &rs, errMsg);
            CHECK_RC;            
            TRACE1(" copyOf select='%s':\n", select);
            DBG(rsPrint(&rs));
            if (rs.type == NodeSetResult) {
                for (i=0; i<rs.nr_nodes; i++) { 
                    if (rs.nodes[i]->nodeType == DOCUMENT_NODE) {
                        child = rs.nodes[i]->firstChild;
                        while (child) {
                            n = domCloneNode(child, 1);
                            domAppendChild(xs->lastNode, n);
                            child = child->nextSibling;
                        }
                    } else {
                        if (*(rs.nodes[i]->nodeName) == '(' &&
                            ((strcmp(rs.nodes[i]->nodeName,"(fragment)")==0)
                             || (strcmp(rs.nodes[i]->nodeName,"(rootNode)")==0))) {
                            child = rs.nodes[i]->firstChild;
                            while (child) {
                                n = domCloneNode(child, 1);
                                domAppendChild(xs->lastNode, n);
                                child = child->nextSibling;
                            }
                        } else {










                            n = domCloneNode(rs.nodes[i], 1);
                            domAppendChild(xs->lastNode, n);
                        }
                    }
                }
            } else
                if ((rs.type == AttrNodeSetResult) ||
                    (rs.type == AttrValueSetResult)) {
                    for (i=0; i<rs.nr_nodes; i++) { 
                        attr = (domAttrNode*)rs.nodes[i];
                        domSetAttribute(xs->lastNode, 
                                        attr->nodeName, attr->nodeValue);
                    }
                } 
                else {
                    str = xpathFuncString( &rs );
                    TRACE1("copyOf: xpathString='%s' \n", str);
                    domAppendNewTextNode(xs->lastNode, str, strlen(str),
                                         TEXT_NODE, 0);
                    free(str);
                }
            xpathRSFree( &rs );               

            break;
            
        case decimalFormat: return 0;
        
        case element:
            nsAT = getAttr(actionNode, "namespace", a_namespace);
            str  = getAttr(actionNode, "name", a_name);
            if (!str) {
                reportError (actionNode, "xsl:element: missing mandatory attribute \"name\".", errMsg);
                return -1;
            }
            
            rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                    str, &str2, errMsg);
            CHECK_RC;
                
            ns = NULL;
            if (nsAT) {
                rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                        nsAT, &ns, errMsg);
                CHECK_RC;
            }
            savedLastNode = xs->lastNode;
            xs->lastNode = domAppendNewElementNode (xs->lastNode, str2, ns);
            free(str2);
            str = getAttr(actionNode, "use-attribute-sets", a_useAttributeSets);
            if (str) {
                TRACE1("use-attribute-sets = '%s' \n", str);
                rc = ExecUseAttributeSets (xs, context, currentNode, currentPos,
                                           str, errMsg);
                CHECK_RC;
            }
            /* process the children as well */
            if (actionNode->firstChild) {
                rc = ExecActions(xs, context, currentNode, currentPos,
                                 actionNode->firstChild, errMsg);
            }
            xs->lastNode = savedLastNode;
            CHECK_RC;

            break;
            
        case fallback: return 0;
            
        case forEach:
            select = getAttr(actionNode, "select", a_select);
            if (!select) {
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375

            if ((rs.type == NodeSetResult) 
                || (rs.type == AttrNodeSetResult)
                || (rs.type == AttrValueSetResult)
                || (rs.type == MixedSetResult)) {

                rc = doSortActions (xs, &rs, actionNode, context, currentNode,
                                    currentPos, &sorted, errMsg);
                CHECK_RC;
                /* should not be necessary, because every node set is
                   returned already in doc Order */
                /*  if (!sorted) sortByDocOrder(&rs); */

                TRACE1(" forEach for select = '%s': (SORTED)\n", select);
                DBG(rsPrint(&rs));







|







3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671

            if ((rs.type == NodeSetResult) 
                || (rs.type == AttrNodeSetResult)
                || (rs.type == AttrValueSetResult)
                || (rs.type == MixedSetResult)) {

                rc = doSortActions (xs, &rs, actionNode, context, currentNode,
                                    currentPos, errMsg);
                CHECK_RC;
                /* should not be necessary, because every node set is
                   returned already in doc Order */
                /*  if (!sorted) sortByDocOrder(&rs); */

                TRACE1(" forEach for select = '%s': (SORTED)\n", select);
                DBG(rsPrint(&rs));
3403
3404
3405
3406
3407
3408
3409



3410
3411
3412
3413
3414
3415
3416
                xpathRSFree( &rs ); 
                if (b) {
                    /* process the children as well */
                    rc = ExecActions(xs, context, currentNode, currentPos,
                                     actionNode->firstChild, errMsg);
                    CHECK_RC;
                }



            }
            break;

        case import:
        case include:
        case key:
            return 0;







>
>
>







3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
                xpathRSFree( &rs ); 
                if (b) {
                    /* process the children as well */
                    rc = ExecActions(xs, context, currentNode, currentPos,
                                     actionNode->firstChild, errMsg);
                    CHECK_RC;
                }
            } else {
                reportError (actionNode, "xsl:if: missing mandatory attribute \"test\".", errMsg);
                return -1;
            }
            break;

        case import:
        case include:
        case key:
            return 0;
3434
3435
3436
3437
3438
3439
3440




3441
3442
3443
3444
3445
3446
3447
                return -1;
            }
            return 0;
            
        case namespaceAlias: return 0;
        
        case number:




            rc = xsltNumber(xs, context, currentNode, currentPos,
                            actionNode, errMsg);
            CHECK_RC;
            break;
        
        case output:
        case otherwise:







>
>
>
>







3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
                return -1;
            }
            return 0;
            
        case namespaceAlias: return 0;
        
        case number:
            if (actionNode->firstChild) {
                reportError (actionNode, "xsl:number has to be empty.", errMsg);
                return -1;
            }
            rc = xsltNumber(xs, context, currentNode, currentPos,
                            actionNode, errMsg);
            CHECK_RC;
            break;
        
        case output:
        case otherwise:
3466
3467
3468
3469
3470
3471
3472



3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487



3488
3489
3490
3491
3492
3493
3494
                        } else {
                            rc = xsltSetVar(xs, 0, str, context, currentNode, 
                                            currentPos, "", NULL, 0, errMsg);
                        }
                    }
                    CHECK_RC;
                }



            }        
            break;
            
        case preserveSpace: return 0;
        
        case procinstr:
            str = getAttr(actionNode, "name", a_name);
            if (str) {
                rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                        str, &str2, errMsg);
                pc = xpathGetTextValue (actionNode, &len);
                n = (domNode*)domNewProcessingInstructionNode(
                                 xs->resultDoc, str2, strlen(str), pc, len);
                domAppendChild(xs->lastNode, n);
                free(str2);



            }
            break;
            
        case sort:
        case stylesheet: 
        case stripSpace:
        case template:







>
>
>
|














>
>
>







3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
                        } else {
                            rc = xsltSetVar(xs, 0, str, context, currentNode, 
                                            currentPos, "", NULL, 0, errMsg);
                        }
                    }
                    CHECK_RC;
                }
            } else {
                reportError (actionNode, "xsl:param: missing mandatory attribute \"name\".", errMsg);
                return -1;
            }
            break;
            
        case preserveSpace: return 0;
        
        case procinstr:
            str = getAttr(actionNode, "name", a_name);
            if (str) {
                rc = evalAttrTemplates( xs, context, currentNode, currentPos,
                                        str, &str2, errMsg);
                pc = xpathGetTextValue (actionNode, &len);
                n = (domNode*)domNewProcessingInstructionNode(
                                 xs->resultDoc, str2, strlen(str), pc, len);
                domAppendChild(xs->lastNode, n);
                free(str2);
            } else {
                reportError (actionNode, "xsl:processing-instruction: missing mandatory attribute \"name\".", errMsg);
                return -1;
            }
            break;
            
        case sort:
        case stylesheet: 
        case stripSpace:
        case template:
3503
3504
3505
3506
3507
3508
3509




3510
3511
3512
3513
3514
3515
3516
            DBG(fprintf(stderr, "text: pc='%s'%d \n", pc, len);)
            domAppendNewTextNode(xs->lastNode, pc, len, TEXT_NODE, disableEsc);
            break;
            
        case transform: return 0;
        
        case valueOf:




            str = getAttr(actionNode, "disable-output-escaping", a_disableOutputEscaping);
            if (str) {
                if (strcmp (str, "yes")==0) disableEsc = 1;
            }
            str = getAttr(actionNode, "select", a_select);
            if (str) {
                TRACE1("valueOf: str='%s' \n", str);







>
>
>
>







3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
            DBG(fprintf(stderr, "text: pc='%s'%d \n", pc, len);)
            domAppendNewTextNode(xs->lastNode, pc, len, TEXT_NODE, disableEsc);
            break;
            
        case transform: return 0;
        
        case valueOf:
            if (actionNode->firstChild) {
                reportError (actionNode, "xsl:value-of has to be empty.", errMsg);
                return -1;
            }
            str = getAttr(actionNode, "disable-output-escaping", a_disableOutputEscaping);
            if (str) {
                if (strcmp (str, "yes")==0) disableEsc = 1;
            }
            str = getAttr(actionNode, "select", a_select);
            if (str) {
                TRACE1("valueOf: str='%s' \n", str);
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
            if (prefix[0] != '\0') {
                ns = domLookupPrefix (node, prefix);
                if (ns) {
                    if (strcmp (localName, "*")==0) {
                        h = Tcl_CreateHashEntry (&(wsinfo->NSWildcards), ns->uri,
                                                 &hnew);
                        if (!hnew) {
                            f = Tcl_GetHashValue (h);
                            if (*f < precedence) { *f = precedence; }
                        } else {
                            f = (double *) Tcl_Alloc (sizeof (double));
                            *f = precedence;
                            Tcl_SetHashValue (h, f);
                        }
                    } else {
                        Tcl_DStringInit (&dStr);
                        Tcl_DStringAppend (&dStr, ns->uri, -1);
                        Tcl_DStringAppend (&dStr, localName, -1);
                        h = Tcl_CreateHashEntry (&(wsinfo->FQNames), 
                                                 Tcl_DStringValue (&dStr), &hnew);
                        if (!hnew) {
                            f = Tcl_GetHashValue (h);
                            if (*f < precedence) { *f = precedence; }
                        } else {
                            f = (double *) Tcl_Alloc (sizeof (double));
                            *f = precedence;
                            Tcl_SetHashValue (h, f);
                        }
                        Tcl_DStringFree (&dStr);
                    }
                } else {
                    /* ??? error? */
                }
            } else {
                h = Tcl_CreateHashEntry (&(wsinfo->NCNames), start, &hnew);
                if (!hnew) {
                    f = Tcl_GetHashValue (h);
                    if (*f < precedence) { *f = precedence; }
                } else {
                    f = (double *) Tcl_Alloc (sizeof (double));
                    *f = precedence;
                    Tcl_SetHashValue (h, f);
                }
            }







|













|














|







4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
            if (prefix[0] != '\0') {
                ns = domLookupPrefix (node, prefix);
                if (ns) {
                    if (strcmp (localName, "*")==0) {
                        h = Tcl_CreateHashEntry (&(wsinfo->NSWildcards), ns->uri,
                                                 &hnew);
                        if (!hnew) {
                            f = (double *)Tcl_GetHashValue (h);
                            if (*f < precedence) { *f = precedence; }
                        } else {
                            f = (double *) Tcl_Alloc (sizeof (double));
                            *f = precedence;
                            Tcl_SetHashValue (h, f);
                        }
                    } else {
                        Tcl_DStringInit (&dStr);
                        Tcl_DStringAppend (&dStr, ns->uri, -1);
                        Tcl_DStringAppend (&dStr, localName, -1);
                        h = Tcl_CreateHashEntry (&(wsinfo->FQNames), 
                                                 Tcl_DStringValue (&dStr), &hnew);
                        if (!hnew) {
                            f = (double *)Tcl_GetHashValue (h);
                            if (*f < precedence) { *f = precedence; }
                        } else {
                            f = (double *) Tcl_Alloc (sizeof (double));
                            *f = precedence;
                            Tcl_SetHashValue (h, f);
                        }
                        Tcl_DStringFree (&dStr);
                    }
                } else {
                    /* ??? error? */
                }
            } else {
                h = Tcl_CreateHashEntry (&(wsinfo->NCNames), start, &hnew);
                if (!hnew) {
                    f = (double *)Tcl_GetHashValue (h);
                    if (*f < precedence) { *f = precedence; }
                } else {
                    f = (double *) Tcl_Alloc (sizeof (double));
                    *f = precedence;
                    Tcl_SetHashValue (h, f);
                }
            }
4162
4163
4164
4165
4166
4167
4168



4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201




4202
4203
4204
4205
4206
4207
4208
                str = getAttr(node, "name", a_name);
                if (str) {
                    attrSet = (xsltAttrSet*)malloc(sizeof(xsltAttrSet));
                    attrSet->next    = xs->attrSets;
                    attrSet->content = node;
                    attrSet->name    = str;
                    xs->attrSets = attrSet;



                }
                break;

            case param:
                str = getAttr(node, "name", a_name);
                if (!str) {
                    reportError (node, "xsl:param must have a \"name\" attribute.",
                                 errMsg);
                    return -1;
                }
                h = Tcl_CreateHashEntry (&(xs->topLevelVars), str, &hnew);
                if (!hnew) {
                    topLevelVar = Tcl_GetHashValue (h);
                    /* Since imported stylesheets are processed at the
                       point at which they encounters the definitions are
                       already in increasing order of import precedence.
                       Therefor we have only to check, if there is a
                       top level var or parm with the same precedence */ 
                    if (topLevelVar->precedence == precedence) {
                        reportError (node, "There is already a variable or parameter with this name with the same import precedence.", errMsg);
                        return -1;
                    }
                } else {
                    topLevelVar = malloc (sizeof (xsltTopLevelVar));
                    Tcl_SetHashValue (h, topLevelVar);
                }
                topLevelVar->node = node;
                topLevelVar->isParameter = 1;
                topLevelVar->precedence = precedence;
                
                break;
                
            case decimalFormat:




                str = getAttr(node, "name", a_name);
                if (str) {
                    /* a named decimal format */
                    df = xs->decimalFormats->next;
                    while (df) {
                        if (strcmp(df->name, str)==0) {
                            /* already existing, override it */







>
>
>






|





|




















>
>
>
>







4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
                str = getAttr(node, "name", a_name);
                if (str) {
                    attrSet = (xsltAttrSet*)malloc(sizeof(xsltAttrSet));
                    attrSet->next    = xs->attrSets;
                    attrSet->content = node;
                    attrSet->name    = str;
                    xs->attrSets = attrSet;
                } else {
                    reportError (node, "xsl:attribute-set: missing mandatory attribute \"name\".", errMsg);
                    return -1;
                }
                break;

            case param:
                str = getAttr(node, "name", a_name);
                if (!str) {
                    reportError (node, "xsl:param: missing mandatory attribute \"name\".",
                                 errMsg);
                    return -1;
                }
                h = Tcl_CreateHashEntry (&(xs->topLevelVars), str, &hnew);
                if (!hnew) {
                    topLevelVar = (xsltTopLevelVar *)Tcl_GetHashValue (h);
                    /* Since imported stylesheets are processed at the
                       point at which they encounters the definitions are
                       already in increasing order of import precedence.
                       Therefor we have only to check, if there is a
                       top level var or parm with the same precedence */ 
                    if (topLevelVar->precedence == precedence) {
                        reportError (node, "There is already a variable or parameter with this name with the same import precedence.", errMsg);
                        return -1;
                    }
                } else {
                    topLevelVar = malloc (sizeof (xsltTopLevelVar));
                    Tcl_SetHashValue (h, topLevelVar);
                }
                topLevelVar->node = node;
                topLevelVar->isParameter = 1;
                topLevelVar->precedence = precedence;
                
                break;
                
            case decimalFormat:
                if (node->firstChild) {
                    reportError (node, "xsl:decimal-format has to be empty.", errMsg);
                    return -1;
                }
                str = getAttr(node, "name", a_name);
                if (str) {
                    /* a named decimal format */
                    df = xs->decimalFormats->next;
                    while (df) {
                        if (strcmp(df->name, str)==0) {
                            /* already existing, override it */
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301




4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334






4335
4336
4337




4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348




4349
4350
4351



4352
4353
4354
4355




4356
4357
4358



4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
                str = getAttr(node, "zero-digit",         a_zeroDigit);
                str = getAttr(node, "digit",              a_digit);
                str = getAttr(node, "pattern-separator",  a_patternSeparator);
                break;

            case import:
                if (node->firstChild) {
                    reportError (node, "xsl:include has to empty!", errMsg);
                    return -1;
                }
                if (!node->ownerDocument->extResolver) {
                    reportError (node, "need resolver Script to include Stylesheet! (use \"-externalentitycommand\")", errMsg);
                    return -11;
                }
                baseURI = findBaseURI (node);
                href = getAttr (node, "href", a_href);
                if (!href) {
                    reportError (node, "xsl:include must have a \"href\" attribute!",
                                 errMsg);
                    return -11;
                }
                extStyleSheet = getExternalDocument (interp, xs,
                                                       node->ownerDocument, 
                                                       baseURI, href, errMsg);
                if (!extStyleSheet) {
                    return -1;
                }
                childPrecedence = (precedence + *precedenceLowBound) / 2;
                childLowBound = *precedenceLowBound;
                rc = processTopLevel (interp, extStyleSheet->documentElement,
                                      xmlNode, xs, childPrecedence,
                                      &childLowBound, errMsg);
                *precedenceLowBound = childPrecedence;
                if (rc != 0) {
                    return rc;
                }
                break;
                
            case include:
                if (node->firstChild) {
                    reportError (node, "xsl:include has to be empty!", errMsg);
                    return -1;
                }
                if (!node->ownerDocument->extResolver) {
                    reportError (node, "need resolver Script to include Stylesheet! (use \"-externalentitycommand\")", errMsg);
                    return -1;
                }
                baseURI = findBaseURI (node);
                href = getAttr (node, "href", a_href);
                if (!href) {
                    reportError (node, "xsl:include must have a \"href\" attribute!",
                                 errMsg);
                    return -1;
                }
                extStyleSheet = getExternalDocument (interp, xs,
                                                     node->ownerDocument, 
                                                     baseURI, href, errMsg);
                if (!extStyleSheet) {
                    return -1;
                }
                xs->currentXSLTNode = extStyleSheet->documentElement;
                rc = processTopLevel (interp, extStyleSheet->documentElement,
                                      xmlNode, xs, precedence,
                                      precedenceLowBound, errMsg);
                if (rc != 0) {
                    return rc;
                }
                break;
                
            case key:




                name = getAttr(node, "name", a_name);
                if (!name) {
                    reportError (node, "xsl:key requires name attribute!", errMsg);
                    return -1;
                }
                match = getAttr(node, "match", a_match);
                if (!match) {
                    reportError (node, "xsl:key requires match attribute!", errMsg);
                    return -1;
                }
                use = getAttr(node, "use", a_use);
                if (!use) {
                    reportError (node, "xsl:key requires use attribute!", errMsg);
                    return -1;
                }

                keyInfo = (xsltKeyInfo *) ckalloc(sizeof(xsltKeyInfo));
                keyInfo->node = node;
                rc = xpathParse (match, errMsg, &(keyInfo->matchAst), 1);
                CHECK_RC1(keyInfo);
                keyInfo->use       = use;
                rc = xpathParse (use, errMsg, &(keyInfo->useAst), 0);
                CHECK_RC1(keyInfo);
                h = Tcl_CreateHashEntry (&(xs->keyInfos), name, &hnew);
                if (hnew) {
                    keyInfo->next  = NULL;
                } else {
                    keyInfo->next  = Tcl_GetHashValue (h);
                }
                Tcl_SetHashValue (h, keyInfo);
                break;

            case namespaceAlias:






                break;
                
            case output:




                str = getAttr(node, "method", a_method);
                if (str) { xs->outputMethod    = strdup(str); }
                str = getAttr(node, "encoding", a_encoding);
                if (str) { xs->outputEncoding  = strdup(str); }
                str = getAttr(node, "media-type", a_mediaType);
                if (str) { xs->outputMediaType = strdup(str); }
                str = getAttr(node, "doctype-public", a_doctypePublic);
                str = getAttr(node, "doctype-system", a_doctypeSystem);
                break;
                
            case preserveSpace:




                str = getAttr(node, "elements", a_elements);
                if (str) {
                    fillElementList(&(xs->preserveInfo), precedence, node, str);



                }
                break;
                
            case stripSpace:




                str = getAttr(node, "elements", a_elements);
                if (str) {
                    fillElementList(&(xs->stripInfo), precedence, node, str);



                }
                break;
                
            case template:
                rc = xsltAddTemplate (xs, node, precedence, errMsg);
                CHECK_RC;
                break;
                
            case variable:
                str = getAttr(node, "name", a_name);
                if (!str) {
                    reportError (node, "xsl:variable must have a \"name\" attribute.",
                                 errMsg);
                    return -1;
                }
                h = Tcl_CreateHashEntry (&(xs->topLevelVars), str, &hnew);
                if (!hnew) {
                    topLevelVar = Tcl_GetHashValue (h);
                    /* Since imported stylesheets are processed at the
                       point at which they encounters the definitions are
                       already in increasing order of import precedence.
                       Therefor we have only to check, if there is a
                       top level var or parm with the same precedence */
                    if (topLevelVar->precedence == precedence) {
                        reportError (node, "There is already a variable or parameter with this name with the same import precedence.", errMsg);







|




|




|

|




















|



|





|



















>
>
>
>


|




|




|














|





>
>
>
>
>
>



>
>
>
>











>
>
>
>



>
>
>




>
>
>
>



>
>
>

















|







4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
                str = getAttr(node, "zero-digit",         a_zeroDigit);
                str = getAttr(node, "digit",              a_digit);
                str = getAttr(node, "pattern-separator",  a_patternSeparator);
                break;

            case import:
                if (node->firstChild) {
                    reportError (node, "xsl:import has to empty!", errMsg);
                    return -1;
                }
                if (!node->ownerDocument->extResolver) {
                    reportError (node, "need resolver Script to include Stylesheet! (use \"-externalentitycommand\")", errMsg);
                    return -1;
                }
                baseURI = findBaseURI (node);
                href = getAttr (node, "href", a_href);
                if (!href) {
                    reportError (node, "xsl:import: missing mandatory attribute \"href\".",
                                 errMsg);
                    return -1;
                }
                extStyleSheet = getExternalDocument (interp, xs,
                                                       node->ownerDocument, 
                                                       baseURI, href, errMsg);
                if (!extStyleSheet) {
                    return -1;
                }
                childPrecedence = (precedence + *precedenceLowBound) / 2;
                childLowBound = *precedenceLowBound;
                rc = processTopLevel (interp, extStyleSheet->documentElement,
                                      xmlNode, xs, childPrecedence,
                                      &childLowBound, errMsg);
                *precedenceLowBound = childPrecedence;
                if (rc != 0) {
                    return rc;
                }
                break;
                
            case include:
                if (node->firstChild) {
                    reportError (node, "xsl:include has to be empty.", errMsg);
                    return -1;
                }
                if (!node->ownerDocument->extResolver) {
                    reportError (node, "need resolver Script to include Stylesheet. (use \"-externalentitycommand\")", errMsg);
                    return -1;
                }
                baseURI = findBaseURI (node);
                href = getAttr (node, "href", a_href);
                if (!href) {
                    reportError (node, "xsl:include: missing mandatory attribute \"href\".",
                                 errMsg);
                    return -1;
                }
                extStyleSheet = getExternalDocument (interp, xs,
                                                     node->ownerDocument, 
                                                     baseURI, href, errMsg);
                if (!extStyleSheet) {
                    return -1;
                }
                xs->currentXSLTNode = extStyleSheet->documentElement;
                rc = processTopLevel (interp, extStyleSheet->documentElement,
                                      xmlNode, xs, precedence,
                                      precedenceLowBound, errMsg);
                if (rc != 0) {
                    return rc;
                }
                break;
                
            case key:
                if (node->firstChild) {
                    reportError (node, "xsl:key has to be empty.", errMsg);
                    return -1;
                }
                name = getAttr(node, "name", a_name);
                if (!name) {
                    reportError (node, "xsl:key: missing mandatory attribute \"name\".", errMsg);
                    return -1;
                }
                match = getAttr(node, "match", a_match);
                if (!match) {
                    reportError (node, "xsl:key: missing mandatory attribute \"match\".", errMsg);
                    return -1;
                }
                use = getAttr(node, "use", a_use);
                if (!use) {
                    reportError (node, "xsl:key: missing mandatory attribute \"use\".", errMsg);
                    return -1;
                }

                keyInfo = (xsltKeyInfo *) ckalloc(sizeof(xsltKeyInfo));
                keyInfo->node = node;
                rc = xpathParse (match, errMsg, &(keyInfo->matchAst), 1);
                CHECK_RC1(keyInfo);
                keyInfo->use       = use;
                rc = xpathParse (use, errMsg, &(keyInfo->useAst), 0);
                CHECK_RC1(keyInfo);
                h = Tcl_CreateHashEntry (&(xs->keyInfos), name, &hnew);
                if (hnew) {
                    keyInfo->next  = NULL;
                } else {
                    keyInfo->next  = (xsltKeyInfo *)Tcl_GetHashValue (h);
                }
                Tcl_SetHashValue (h, keyInfo);
                break;

            case namespaceAlias:
                if (node->firstChild) {
                    reportError (node, "xsl:namespace-alias has to be empty.",
                                 errMsg);
                    return -1;
                }
                /* mandatory attributes: stylesheet-prefix result-prefix */
                break;
                
            case output:
                if (node->firstChild) {
                    reportError (node, "xsl:output has to be empty.", errMsg);
                    return -1;
                }
                str = getAttr(node, "method", a_method);
                if (str) { xs->outputMethod    = strdup(str); }
                str = getAttr(node, "encoding", a_encoding);
                if (str) { xs->outputEncoding  = strdup(str); }
                str = getAttr(node, "media-type", a_mediaType);
                if (str) { xs->outputMediaType = strdup(str); }
                str = getAttr(node, "doctype-public", a_doctypePublic);
                str = getAttr(node, "doctype-system", a_doctypeSystem);
                break;
                
            case preserveSpace:
                if (node->firstChild) {
                    reportError (node, "xsl:preserve-space has to be empty.", errMsg);
                    return -1;
                }
                str = getAttr(node, "elements", a_elements);
                if (str) {
                    fillElementList(&(xs->preserveInfo), precedence, node, str);
                } else {
                    reportError (node, "xsl:preserve-space: missing required attribute \"elements\".", errMsg);
                    return -1;
                }
                break;
                
            case stripSpace:
                if (node->firstChild) {
                    reportError (node, "xsl:strip-space has to be empty.", errMsg);
                    return -1;
                }
                str = getAttr(node, "elements", a_elements);
                if (str) {
                    fillElementList(&(xs->stripInfo), precedence, node, str);
                } else {
                    reportError (node, "xsl:strip-space: missing required attribute \"elements\".", errMsg);
                    return -1;
                }
                break;
                
            case template:
                rc = xsltAddTemplate (xs, node, precedence, errMsg);
                CHECK_RC;
                break;
                
            case variable:
                str = getAttr(node, "name", a_name);
                if (!str) {
                    reportError (node, "xsl:variable must have a \"name\" attribute.",
                                 errMsg);
                    return -1;
                }
                h = Tcl_CreateHashEntry (&(xs->topLevelVars), str, &hnew);
                if (!hnew) {
                    topLevelVar = (xsltTopLevelVar *)Tcl_GetHashValue (h);
                    /* Since imported stylesheets are processed at the
                       point at which they encounters the definitions are
                       already in increasing order of import precedence.
                       Therefor we have only to check, if there is a
                       top level var or parm with the same precedence */
                    if (topLevelVar->precedence == precedence) {
                        reportError (node, "There is already a variable or parameter with this name with the same import precedence.", errMsg);
4610
4611
4612
4613
4614
4615
4616

4617
4618
4619
4620
4621
4622
4623
    char             ** errMsg,
    domDocument      ** resultDoc   
)
{ 
    xpathResultSet  nodeList;
    domNode        *node;
    int             rc;

    double          precedence, precedenceLowBound;
    xsltState       xs;
    xsltSubDoc     *sdoc;
    
    *errMsg = NULL;  
    
    xmlNode = xmlNode->ownerDocument->rootNode; /* jcl: hack, should pass document */







>







4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
    char             ** errMsg,
    domDocument      ** resultDoc   
)
{ 
    xpathResultSet  nodeList;
    domNode        *node;
    int             rc;
    char           *str;
    double          precedence, precedenceLowBound;
    xsltState       xs;
    xsltSubDoc     *sdoc;
    
    *errMsg = NULL;  
    
    xmlNode = xmlNode->ownerDocument->rootNode; /* jcl: hack, should pass document */
4702
4703
4704
4705
4706
4707
4708





4709

4710
4711
4712
4713
4714
4715
4716
        xsltPopVarFrame (&xs);
        xpathRSFree( &nodeList );
        xs.resultDoc->documentElement = xs.resultDoc->rootNode->firstChild;
        xs.resultDoc->nodeFlags |= OUTPUT_DEFAULT_HTML;
        *resultDoc = xs.resultDoc;
        xsltFreeState (&xs);
        return 0;





    } 

    
    precedence = 1.0;
    precedenceLowBound = 0.0;
    rc = processTopLevel (clientData, node, xmlNode, &xs, precedence,
                          &precedenceLowBound,errMsg);
    if (rc != 0) {
        xsltFreeState (&xs);







>
>
>
>
>
|
>







5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
        xsltPopVarFrame (&xs);
        xpathRSFree( &nodeList );
        xs.resultDoc->documentElement = xs.resultDoc->rootNode->firstChild;
        xs.resultDoc->nodeFlags |= OUTPUT_DEFAULT_HTML;
        *resultDoc = xs.resultDoc;
        xsltFreeState (&xs);
        return 0;
    } else {
        str = getAttr (node, "version", a_version);
        if (!str) {
            reportError (node, "missing mandatory attribute \"version\".", errMsg);
            return -1;
        }
    }
    
    precedence = 1.0;
    precedenceLowBound = 0.0;
    rc = processTopLevel (clientData, node, xmlNode, &xs, precedence,
                          &precedenceLowBound,errMsg);
    if (rc != 0) {
        xsltFreeState (&xs);
Changes to generic/tcldom.c.
28
29
30
31
32
33
34
















35
36
37
38
39
40
41
42
43
|       Sept99  Carsten Zerbst    Added comment and processing instructions
|                                 nodes.
|       June00  Zoran Vasiljevic  Made thread-safe.
|       July00  Zoran Vasiljevic  Added "domNode appendFromScript"
|
|
|   $Log$
















|   Revision 1.1  2002/02/22 01:05:35  rolf
|   Initial revision
|
|
|
|   written by Jochen Loewer
|   April, 1999
|
\---------------------------------------------------------------------------*/







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|







28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|       Sept99  Carsten Zerbst    Added comment and processing instructions
|                                 nodes.
|       June00  Zoran Vasiljevic  Made thread-safe.
|       July00  Zoran Vasiljevic  Added "domNode appendFromScript"
|
|
|   $Log$
|   Revision 1.6  2002/03/10 01:17:21  rolf
|   Added method createDocumentNS to the dom command.
|
|   Revision 1.5  2002/03/07 22:12:10  rolf
|   Freeze of actual state, befor feeding stuff to Jochen.
|
|   Revision 1.4  2002/03/01 01:22:14  rolf
|   Changed parsing. [dom parse ..] now uses Tcl_GetStringFromObj(),
|   dom parse -channel now respects the encoding of the channel.
|
|   Revision 1.3  2002/02/24 02:31:27  rolf
|   Fixed UTF-8 char byte length determination
|
|   Revision 1.2  2002/02/23 01:13:33  rolf
|   Some code tweaking for a mostly warning free MS build
|
|   Revision 1.1.1.1  2002/02/22 01:05:35  rolf
|   tDOM0.7test with Jochens first set of patches
|
|
|
|   written by Jochen Loewer
|   April, 1999
|
\---------------------------------------------------------------------------*/
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
                         Tcl_WrongNumArgs(interp, n, objv, msg); \
                         return TCL_ERROR; \
                     }
#if TclOnly8Bits
#define writeChars(var,chan,buf,len)  (chan) ? \
                     ((void)Tcl_Write ((chan), (buf), (len) )) : \
                     (Tcl_AppendToObj ((var), (buf), (len) ));
#define TCLGETBYTES(obj,pLen) Tcl_GetStringFromObj(obj,pLen)
#else
#define writeChars(var,chan,buf,len)  (chan) ? \
                     ((void)Tcl_WriteChars ((chan), (buf), (len) )) : \
                     (Tcl_AppendToObj ((var), (buf), (len) ));
#define TCLGETBYTES(obj,pLen) Tcl_GetByteArrayFromObj(obj,pLen)
#endif          
/*----------------------------------------------------------------------------
|   Module Globals
|
\---------------------------------------------------------------------------*/
#ifndef TCL_THREADS








<




<







113
114
115
116
117
118
119

120
121
122
123

124
125
126
127
128
129
130
                         Tcl_WrongNumArgs(interp, n, objv, msg); \
                         return TCL_ERROR; \
                     }
#if TclOnly8Bits
#define writeChars(var,chan,buf,len)  (chan) ? \
                     ((void)Tcl_Write ((chan), (buf), (len) )) : \
                     (Tcl_AppendToObj ((var), (buf), (len) ));

#else
#define writeChars(var,chan,buf,len)  (chan) ? \
                     ((void)Tcl_WriteChars ((chan), (buf), (len) )) : \
                     (Tcl_AppendToObj ((var), (buf), (len) ));

#endif          
/*----------------------------------------------------------------------------
|   Module Globals
|
\---------------------------------------------------------------------------*/
#ifndef TCL_THREADS

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
                              
static char * tcldom_docTrace (ClientData  clientData,
                               Tcl_Interp *interp,
                               char       *name1,
                               char       *name2,
                               int        flags  );
                               

/*----------------------------------------------------------------------------
|   UtfCount     
|
\---------------------------------------------------------------------------*/
#if !TclOnly8Bits
static int
UtfCount(
    int ch
)
{
    if ((ch > 0) && (ch < 0x80)) { return 1; }
    if (ch <= 0x7FF)             { return 2; }
    if (ch <= 0xFFFF)            { return 3; } 
    return 0;
}
#endif


/*----------------------------------------------------------------------------
|   tcldom_docDeleteNode
|
\---------------------------------------------------------------------------*/
static void
tcldom_docDeleteNode (
    domNode  * node,







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







269
270
271
272
273
274
275



















276
277
278
279
280
281
282
                              
static char * tcldom_docTrace (ClientData  clientData,
                               Tcl_Interp *interp,
                               char       *name1,
                               char       *name2,
                               int        flags  );
                               



















/*----------------------------------------------------------------------------
|   tcldom_docDeleteNode
|
\---------------------------------------------------------------------------*/
static void
tcldom_docDeleteNode (
    domNode  * node,
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
        dinfo->traceVarName = NULL;

        Tcl_CreateObjCommand ( interp, objCmdName, 
                                      (Tcl_ObjCmdProc *)  tcldom_DocObjCmd,
                                      (ClientData)        dinfo, 
                                      (Tcl_CmdDeleteProc*)tcldom_docCmdDeleteProc );
    } else {
        /* reuse old information */
        dinfo = (TcldomDocDeleteInfo*)cmd_info.objClientData;
    }
    if (setVariable) {
        objVar = Tcl_GetStringFromObj (var_name, NULL);
        dinfo->traceVarName = strdup(objVar);
        Tcl_UnsetVar (interp, objVar, 0);                                    
        Tcl_SetVar   (interp, objVar, objCmdName, 0);







|







525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
        dinfo->traceVarName = NULL;

        Tcl_CreateObjCommand ( interp, objCmdName, 
                                      (Tcl_ObjCmdProc *)  tcldom_DocObjCmd,
                                      (ClientData)        dinfo, 
                                      (Tcl_CmdDeleteProc*)tcldom_docCmdDeleteProc );
    } else {
        /* reuse old informaion */
        dinfo = (TcldomDocDeleteInfo*)cmd_info.objClientData;
    }
    if (setVariable) {
        objVar = Tcl_GetStringFromObj (var_name, NULL);
        dinfo->traceVarName = strdup(objVar);
        Tcl_UnsetVar (interp, objVar, 0);                                    
        Tcl_SetVar   (interp, objVar, objCmdName, 0);
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
    GetTcldomTSD()
    char        *xml_string;
    int          xml_string_len;
    domDocument *doc;
    XML_Parser   parser;
    
    
    xml_string = TCLGETBYTES( obj, &xml_string_len);

#ifdef TDOM_NO_EXPAT
    Tcl_AppendResult(interp, "tDOM was compiled without Expat!", NULL);
    return TCL_ERROR;
#else    
    parser = XML_ParserCreate(NULL);     








|







873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
    GetTcldomTSD()
    char        *xml_string;
    int          xml_string_len;
    domDocument *doc;
    XML_Parser   parser;
    
    
    xml_string = Tcl_GetStringFromObj( obj, &xml_string_len);

#ifdef TDOM_NO_EXPAT
    Tcl_AppendResult(interp, "tDOM was compiled without Expat!", NULL);
    return TCL_ERROR;
#else    
    parser = XML_ParserCreate(NULL);     

1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
#if TclOnly8Bits                              
        } else {
            AP(*pc)
        }
#else
        } else {
        if ((unsigned char)*pc > 127) {
                clen = UtfCount (*pc);
                if (!clen) {
                    fprintf (stderr, "can only handle UTF-8 chars up to 3 bytes long.");
                    exit(1);
                }
            for (i = 0; i < clen; i++) {
                AP(*pc);
                pc++;







|







1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
#if TclOnly8Bits                              
        } else {
            AP(*pc)
        }
#else
        } else {
        if ((unsigned char)*pc > 127) {
                clen = UTF8_CHAR_LEN(*pc);
                if (!clen) {
                    fprintf (stderr, "can only handle UTF-8 chars up to 3 bytes long.");
                    exit(1);
                }
            for (i = 0; i < clen; i++) {
                AP(*pc);
                pc++;
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
    char *baseURI = NULL;
    Tcl_HashEntry *entryPtr;

    do {
        if (node->nodeFlags & HAS_BASEURI) {
            entryPtr = Tcl_FindHashEntry (node->ownerDocument->baseURIs,
                                          (char*)node->nodeNumber);
            baseURI = Tcl_GetHashValue (entryPtr);
            break;
        }
        if (node->previousSibling) {
            node = node->previousSibling;
        }
        else {
            node = node->parentNode;







|







1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
    char *baseURI = NULL;
    Tcl_HashEntry *entryPtr;

    do {
        if (node->nodeFlags & HAS_BASEURI) {
            entryPtr = Tcl_FindHashEntry (node->ownerDocument->baseURIs,
                                          (char*)node->nodeNumber);
            baseURI = (char *)Tcl_GetHashValue (entryPtr);
            break;
        }
        if (node->previousSibling) {
            node = node->previousSibling;
        }
        else {
            node = node->parentNode;
2995
2996
2997
2998
2999
3000
3001
3002



































3003
3004
3005
3006
3007
3008
3009
    
    CheckArgs (2,3,1,"docElemName ?newObjVar?");
    
    if (objc == 3) {    
        newObjName = objv[2];
        setVariable = 1;
    }
    doc = domCreateDocument ( Tcl_GetStringFromObj (objv[1], NULL) );



































    return tcldom_returnDocumentObj( 
                 interp, doc, setVariable, newObjName
    );
}


/*----------------------------------------------------------------------------







|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
    
    CheckArgs (2,3,1,"docElemName ?newObjVar?");
    
    if (objc == 3) {    
        newObjName = objv[2];
        setVariable = 1;
    }
    doc = domCreateDocument ( interp, Tcl_GetStringFromObj (objv[1], NULL),
                              NULL);
    if (!doc) return TCL_ERROR;
    return tcldom_returnDocumentObj( 
                 interp, doc, setVariable, newObjName
    );
}



/*----------------------------------------------------------------------------
|   tcldom_createDocumentNS
|
\---------------------------------------------------------------------------*/
static 
int tcldom_createDocumentNS (
    ClientData  clientData,
    Tcl_Interp *interp,
    int         objc,
    Tcl_Obj    * const objv[]
) 
{
    int          setVariable = 0;
    domDocument *doc;
    Tcl_Obj     *newObjName = NULL;    
    
    
    CheckArgs (3,4,1,"docElemName uri ?newObjVar?");
    
    if (objc == 4) {    
        newObjName = objv[3];
        setVariable = 1;
    }
    doc = domCreateDocument ( interp, Tcl_GetStringFromObj (objv[1], NULL), 
                              Tcl_GetStringFromObj (objv[2], NULL) );
    if (!doc) return TCL_ERROR;
    return tcldom_returnDocumentObj( 
                 interp, doc, setVariable, newObjName
    );
}


/*----------------------------------------------------------------------------
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
    }
    
    if (chan == NULL) {
        if (objc < 2) {
            SetResult (dom_usage);
            return TCL_ERROR;
        }
        xml_string = TCLGETBYTES( objv[1], &xml_string_len);
        if (objc == 3) {    
            newObjName = objv[2];
            setVariable = 1;
        }
    } else {
        xml_string = NULL;
        if (takeSimpleParser || takeHTMLParser) {







|







3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
    }
    
    if (chan == NULL) {
        if (objc < 2) {
            SetResult (dom_usage);
            return TCL_ERROR;
        }
        xml_string = Tcl_GetStringFromObj( objv[1], &xml_string_len);
        if (objc == 3) {    
            newObjName = objv[2];
            setVariable = 1;
        }
    } else {
        xml_string = NULL;
        if (takeSimpleParser || takeHTMLParser) {
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
    GetTcldomTSD()
    char        * method, tmp[300];
    int           methodIndex, result, i, bool;
    Tcl_CmdInfo   cmdInfo;
    Tcl_Obj     * mobjv[MAX_REWRITE_ARGS];
        
    static char *domMethods[] = {
        "createDocument",    "createNodeCmd",     "parse", 
        "setResultEncoding", "setStoreLineColumn",
        NULL
    };
    enum domMethod {
        m_createDocument,    m_createNodeCmd,     m_parse, 
        m_setResultEncoding, m_setStoreLineColumn
    };
   


    if (objc < 2) {
        SetResult ( dom_usage);
        return TCL_ERROR;







|
|



|
|







3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
    GetTcldomTSD()
    char        * method, tmp[300];
    int           methodIndex, result, i, bool;
    Tcl_CmdInfo   cmdInfo;
    Tcl_Obj     * mobjv[MAX_REWRITE_ARGS];
        
    static char *domMethods[] = {
        "createDocument",  "createDocumentNS",  "createNodeCmd",
        "parse",           "setResultEncoding", "setStoreLineColumn",
        NULL
    };
    enum domMethod {
        m_createDocument,    m_createDocumentNS,  m_createNodeCmd,
        m_parse,             m_setResultEncoding, m_setStoreLineColumn
    };
   


    if (objc < 2) {
        SetResult ( dom_usage);
        return TCL_ERROR;
3352
3353
3354
3355
3356
3357
3358




3359
3360
3361
3362
3363
3364
3365
    }    
    CheckArgs (2,10,1,dom_usage);
    switch ((enum domMethod) methodIndex ) {
       
        case m_createDocument:
            return tcldom_createDocument (clientData, interp, --objc, objv+1 );





        case m_createNodeCmd:
            return nodecmd_createNodeCmd (clientData, interp, --objc, objv+1 );
            
        case m_parse:
            return tcldom_parse (clientData, interp, --objc, objv+1 );

        case m_setResultEncoding:







>
>
>
>







3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
    }    
    CheckArgs (2,10,1,dom_usage);
    switch ((enum domMethod) methodIndex ) {
       
        case m_createDocument:
            return tcldom_createDocument (clientData, interp, --objc, objv+1 );

        case m_createDocumentNS:
            return tcldom_createDocumentNS (clientData, interp, --objc,
                                            objv+1);

        case m_createNodeCmd:
            return nodecmd_createNodeCmd (clientData, interp, --objc, objv+1 );
            
        case m_parse:
            return tcldom_parse (clientData, interp, --objc, objv+1 );

        case m_setResultEncoding:
Changes to generic/tcldom.h.
24
25
26
27
28
29
30



31
32
33
34
35
36
37
38
39
|   Portions created by Jochen Loewer are Copyright (C) 1998, 1999
|   Jochen Loewer. All Rights Reserved.
|
|   Contributor(s):
|
|
|   $Log$



|   Revision 1.1  2002/02/22 01:05:34  rolf
|   Initial revision
|
|
|
|   written by Jochen Loewer
|   April, 1999
|
\---------------------------------------------------------------------------*/







>
>
>
|
|







24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|   Portions created by Jochen Loewer are Copyright (C) 1998, 1999
|   Jochen Loewer. All Rights Reserved.
|
|   Contributor(s):
|
|
|   $Log$
|   Revision 1.2  2002/02/23 01:13:33  rolf
|   Some code tweaking for a mostly warning free MS build
|
|   Revision 1.1.1.1  2002/02/22 01:05:34  rolf
|   tDOM0.7test with Jochens first set of patches
|
|
|
|   written by Jochen Loewer
|   April, 1999
|
\---------------------------------------------------------------------------*/
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

Tcl_ObjCmdProc tcldom_domCmd;     
Tcl_ObjCmdProc tcldom_NodeObjCmd; 
Tcl_ObjCmdProc TclExpatObjCmd;
Tcl_ObjCmdProc tcldom_unknownCmd;
Tcl_ObjCmdProc TclTdomObjCmd;

#define STR_TDOM_VERSION(v) ("0.7")
#ifndef DLLEXPORT
#define DLL_BUILD
#  undef TCL_STORAGE_CLASS
#  define TCL_STORAGE_CLASS
#   define DLLEXPORT __declspec(dllexport)
#ifndef STATIC_BUILD
#if defined(_MSC_VER)
#   define EXPORT(a,b) __declspec(dllexport) a b
#   define DllEntryPoint DllMain
#else
#   if defined(__BORLANDC__)
#       define EXPORT(a,b) a _export b
#   else
#       define EXPORT(a,b) a b
#   endif
#endif
#endif
#endif
#endif








<
<
|

|
<
<
<
<
<
|
|
|
|
|
|

|
<
<

50
51
52
53
54
55
56


57
58
59





60
61
62
63
64
65
66
67


68

Tcl_ObjCmdProc tcldom_domCmd;     
Tcl_ObjCmdProc tcldom_NodeObjCmd; 
Tcl_ObjCmdProc TclExpatObjCmd;
Tcl_ObjCmdProc tcldom_unknownCmd;
Tcl_ObjCmdProc TclTdomObjCmd;



#if defined(_MSC_VER)
#  undef TCL_STORAGE_CLASS
#  define TCL_STORAGE_CLASS DLLEXPORT





#endif

#define STR_TDOM_VERSION(v) ("0.7")

EXTERN int Tdom_Init     _ANSI_ARGS_((Tcl_Interp *interp));

#endif




Changes to generic/tclexpat.c.
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <io.h>
#endif

#ifdef _POSIX_SOURCE
#include <unistd.h>
#endif

#undef  TCL_STORAGE_CLASS
#define TCL_STORAGE_CLASS DLLEXPORT

/* Used internal als status, like TCL_OK, TCL_ERROR etc.  As a
   consequent, application specific error codes must be at least
   greater than 5 */
#define ERROR_IN_EXTREFHANDLER 5

#define READ_SIZE (1024*8)
#ifndef O_BINARY







<
<
<







42
43
44
45
46
47
48



49
50
51
52
53
54
55
#include <io.h>
#endif

#ifdef _POSIX_SOURCE
#include <unistd.h>
#endif




/* Used internal als status, like TCL_OK, TCL_ERROR etc.  As a
   consequent, application specific error codes must be at least
   greater than 5 */
#define ERROR_IN_EXTREFHANDLER 5

#define READ_SIZE (1024*8)
#ifndef O_BINARY
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
                     }
#define CheckDefaultTclHandlerSet \
                      if (!activeTclHandlerSet) { \
                         activeTclHandlerSet = CreateTclHandlerSet("default");\
                         expat->firstTclHandlerSet = activeTclHandlerSet; \
                      }

#if ((TCL_MAJOR_VERSION == 8) && (TCL_MINOR_VERSION > 0))
#define TCLGETBYTES(obj,pLen) Tcl_GetByteArrayFromObj(obj,pLen)
#define TCLNEWBYTES(obj,len)  Tcl_NewByteArrayObj(obj,len)
#else
#define TCLGETBYTES(obj,pLen) Tcl_GetStringFromObj(obj,pLen)
#define TCLNEWBYTES(obj,len)  Tcl_NewStringObj(obj,len)
#endif

/*----------------------------------------------------------------------------
|   typedefs
|
\---------------------------------------------------------------------------*/

typedef enum {







<
<
<
<
<
<
<







79
80
81
82
83
84
85







86
87
88
89
90
91
92
                     }
#define CheckDefaultTclHandlerSet \
                      if (!activeTclHandlerSet) { \
                         activeTclHandlerSet = CreateTclHandlerSet("default");\
                         expat->firstTclHandlerSet = activeTclHandlerSet; \
                      }









/*----------------------------------------------------------------------------
|   typedefs
|
\---------------------------------------------------------------------------*/

typedef enum {
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
     ClientData clientData;
     Tcl_Interp *interp;
     int objc;
     Tcl_Obj *CONST objv[];
{
  TclGenExpatInfo *expat = (TclGenExpatInfo *) clientData;
  char *data;
  int len, optionIndex, result = TCL_OK;
  CHandlerSet *activeCHandlerSet;

  static char *options[] = {
      "configure", "cget", "free", "get",
      "parse", "parsechannel", "parsefile", "reset", NULL
  };
  enum options {







|







589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
     ClientData clientData;
     Tcl_Interp *interp;
     int objc;
     Tcl_Obj *CONST objv[];
{
  TclGenExpatInfo *expat = (TclGenExpatInfo *) clientData;
  char *data;
  int len = 0, optionIndex, result = TCL_OK;
  CHandlerSet *activeCHandlerSet;

  static char *options[] = {
      "configure", "cget", "free", "get",
      "parse", "parsechannel", "parsefile", "reset", NULL
  };
  enum options {
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
      /* [email protected], 1999.6.28 */
      result = TclExpatGet(interp, expat, objc - 2, objv + 2);
      break;

    case EXPAT_PARSE:

      CheckArgs (3,3,2,"<XML-String>");
      data = TCLGETBYTES(objv[2], &len);
      result = TclExpatParse(interp, expat, data, len, EXPAT_INPUT_STRING);
      break;

    case EXPAT_PARSECHANNEL:

      CheckArgs (3,3,2,"<Tcl-Channel>");
      data = Tcl_GetStringFromObj (objv[2], NULL);







|







635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
      /* [email protected], 1999.6.28 */
      result = TclExpatGet(interp, expat, objc - 2, objv + 2);
      break;

    case EXPAT_PARSE:

      CheckArgs (3,3,2,"<XML-String>");
      data = Tcl_GetStringFromObj(objv[2], &len);
      result = TclExpatParse(interp, expat, data, len, EXPAT_INPUT_STRING);
      break;

    case EXPAT_PARSECHANNEL:

      CheckArgs (3,3,2,"<Tcl-Channel>");
      data = Tcl_GetStringFromObj (objv[2], NULL);
724
725
726
727
728
729
730
731





732
733
734
735
736
737
738
{
  int result, mode, bytesread, done;
  char s[255], buf[8*1024];
  int fd;
  XML_Parser *parser;
  Tcl_Channel channel = NULL;
  CHandlerSet *activeCHandlerSet;
  






  expat->status = TCL_OK;
  if (expat->result != NULL) {
    Tcl_DecrRefCount(expat->result);
  }

  activeCHandlerSet = expat->firstCHandlerSet;







|
>
>
>
>
>







714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
{
  int result, mode, bytesread, done;
  char s[255], buf[8*1024];
  int fd;
  XML_Parser *parser;
  Tcl_Channel channel = NULL;
  CHandlerSet *activeCHandlerSet;
#if !TclOnly8Bits    
  Tcl_Obj       *bufObj;
  Tcl_DString    dStr;
  int            useBinary;
  char          *str;
#endif

  expat->status = TCL_OK;
  if (expat->result != NULL) {
    Tcl_DecrRefCount(expat->result);
  }

  activeCHandlerSet = expat->firstCHandlerSet;
763
764
765
766
767
768
769






































770
771
772
773
774
775
776
777
778
779
780
781

782
783
784
785
786
787
788
789
790
          return TCL_ERROR;
      }
      if (!(mode & TCL_READABLE)) {
          Tcl_ResetResult (interp);
          Tcl_AppendResult (interp, "channel \"", data, "wasn't opened for reading", (char *) NULL);
          return TCL_ERROR;
      }






































      do {
          bytesread = Tcl_Read (channel, buf, sizeof (buf));
          done = bytesread < sizeof (buf);
          if (done) {
              result = XML_Parse (expat->parser, buf, bytesread, done);
          } else {
              if (!XML_Parse (expat->parser, buf, bytesread, done)) {
                  result = 0;
                  break;
              }
          }
      } while (!done);

      break;

  case EXPAT_INPUT_FILENAME:
      fd = open(data, O_BINARY|O_RDONLY);
      if (fd < 0) {
          Tcl_ResetResult (interp);
          Tcl_AppendResult (interp, "error opening file \"",
                            data, "\"", (char *) NULL);
          return TCL_ERROR;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|



>

|







758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
          return TCL_ERROR;
      }
      if (!(mode & TCL_READABLE)) {
          Tcl_ResetResult (interp);
          Tcl_AppendResult (interp, "channel \"", data, "wasn't opened for reading", (char *) NULL);
          return TCL_ERROR;
      }
#if !TclOnly8Bits
      Tcl_DStringInit (&dStr);
      if (Tcl_GetChannelOption (interp, channel, "-encoding", &dStr) != TCL_OK) {
          return TCL_ERROR;
      }
      if (strcmp (Tcl_DStringValue (&dStr), "binary")==0 ) useBinary = 1;
      else useBinary = 0;
      Tcl_DStringFree (&dStr);
      if (useBinary) {
          do {
              bytesread = Tcl_Read (channel, buf, sizeof (buf));
              done = bytesread < sizeof (buf);
              if (done) {
                  result = XML_Parse (expat->parser, buf, bytesread, done);
              } else {
                  if (!XML_Parse (expat->parser, buf, bytesread, done)) {
                      result = 0;
                      break;
                  }
              }
          } while (!done);
      } else {
          bufObj = Tcl_NewObj();
          Tcl_IncrRefCount (bufObj);
          Tcl_SetObjLength (bufObj, 6144);
          do {
              len = Tcl_ReadChars (channel, bufObj, 1024, 0);
              done = (len < 1024);
              str = Tcl_GetStringFromObj (bufObj, &len);
              if (!XML_Parse (expat->parser, str, len, done)) {
                  result = 0;
                  break;
              }
          } while (!done);
          result = 1;
          Tcl_DecrRefCount (bufObj);
      }
#else             
      do {
          bytesread = Tcl_Read (channel, buf, sizeof (buf));
          done = bytesread < sizeof (buf);
          if (done) {
              result = XML_Parse (expat->parser, buf, bytesread, done);
          } else {
              if (!XML_Parse (expat->parser, buf, bytesread, done)) {
                  result = 0;
                      break;
              }
          }
      } while (!done);
#endif      
      break;
      
  case EXPAT_INPUT_FILENAME:
      fd = open(data, O_BINARY|O_RDONLY);
      if (fd < 0) {
          Tcl_ResetResult (interp);
          Tcl_AppendResult (interp, "error opening file \"",
                            data, "\"", (char *) NULL);
          return TCL_ERROR;
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
       */
      if (activeTclHandlerSet->ignoreWhiteCDATAs && onlyWhiteSpace) {
          goto nextTcl;
      }

      vector[0] = activeTclHandlerSet->datacommand;
      vector[1] = Tcl_NewStringObj ((char *)s, len);
/*        vector[1] = TCLNEWBYTES((char *)s, len); */
      Tcl_Preserve((ClientData) expat->interp);
      result = activeTclHandlerSet->datacommandObjProc(activeTclHandlerSet->datacommandclientData, expat->interp, 2, vector);
      Tcl_Release((ClientData) expat->interp);

      TclExpatHandlerResult(expat, activeTclHandlerSet, result);
  nextTcl:
      activeTclHandlerSet = activeTclHandlerSet->nextHandlerSet;







<







2031
2032
2033
2034
2035
2036
2037

2038
2039
2040
2041
2042
2043
2044
       */
      if (activeTclHandlerSet->ignoreWhiteCDATAs && onlyWhiteSpace) {
          goto nextTcl;
      }

      vector[0] = activeTclHandlerSet->datacommand;
      vector[1] = Tcl_NewStringObj ((char *)s, len);

      Tcl_Preserve((ClientData) expat->interp);
      result = activeTclHandlerSet->datacommandObjProc(activeTclHandlerSet->datacommandclientData, expat->interp, 2, vector);
      Tcl_Release((ClientData) expat->interp);

      TclExpatHandlerResult(expat, activeTclHandlerSet, result);
  nextTcl:
      activeTclHandlerSet = activeTclHandlerSet->nextHandlerSet;
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
static void
generateModel (interp, rep, model)
    Tcl_Interp  *interp;
    Tcl_Obj     *rep;
    XML_Content *model;
{
    Tcl_Obj *cp, *detail;
    int      i;


    switch (model->type) {
    case XML_CTYPE_EMPTY:
        Tcl_ListObjAppendElement (interp, rep, Tcl_NewStringObj ("EMPTY", 5));
        break;
    case XML_CTYPE_ANY:







|







3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
static void
generateModel (interp, rep, model)
    Tcl_Interp  *interp;
    Tcl_Obj     *rep;
    XML_Content *model;
{
    Tcl_Obj *cp, *detail;
    unsigned int      i;


    switch (model->type) {
    case XML_CTYPE_EMPTY:
        Tcl_ListObjAppendElement (interp, rep, Tcl_NewStringObj ("EMPTY", 5));
        break;
    case XML_CTYPE_ANY:
Changes to generic/tclexpat.h.
125
126
127
128
129
130
131




132
133
134
135
136
137
138
} TclGenExpatInfo;

/*--------------------------------------------------------------------------
|   Function prototypes
|
\-------------------------------------------------------------------------*/






EXTERN int TclExpatObjCmd _ANSI_ARGS_((ClientData dummy,
                                       Tcl_Interp *interp, 
                                       int objc, Tcl_Obj *CONST objv[]));  
EXTERN int CheckExpatParserObj _ANSI_ARGS_((Tcl_Interp *interp, 
                                            Tcl_Obj *CONST nameObj));
EXTERN int CHandlerSetInstall _ANSI_ARGS_((Tcl_Interp *interp,







>
>
>
>







125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
} TclGenExpatInfo;

/*--------------------------------------------------------------------------
|   Function prototypes
|
\-------------------------------------------------------------------------*/

#if defined(_MSC_VER)
#  undef TCL_STORAGE_CLASS
#  define TCL_STORAGE_CLASS DLLEXPORT
#endif

EXTERN int TclExpatObjCmd _ANSI_ARGS_((ClientData dummy,
                                       Tcl_Interp *interp, 
                                       int objc, Tcl_Obj *CONST objv[]));  
EXTERN int CheckExpatParserObj _ANSI_ARGS_((Tcl_Interp *interp, 
                                            Tcl_Obj *CONST nameObj));
EXTERN int CHandlerSetInstall _ANSI_ARGS_((Tcl_Interp *interp,
Changes to generic/tdominit.c.
24
25
26
27
28
29
30



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|   Portions created by Jochen Loewer are Copyright (C) 1998, 1999
|   Jochen Loewer. All Rights Reserved.
|
|   Contributor(s):
|
|
|   $Log$



|   Revision 1.1  2002/02/22 01:05:35  rolf
|   Initial revision
|
|
|
|   written by Jochen Loewer
|   April, 1999
|
\---------------------------------------------------------------------------*/



/*----------------------------------------------------------------------------
|   Includes
|
\---------------------------------------------------------------------------*/
#include <tcl.h>
#include <dom.h>
#include <tcldom.h>


/*JCL #define STR_TDOM_VERSION(v) (#v)

EXTERN EXPORT(int,Tdom_Init)     _ANSI_ARGS_((Tcl_Interp *interp));
*/


/*
 *----------------------------------------------------------------------------
 *
 * Tdom_Init --
 *
 *	Initialization routine for loadable module







>
>
>
|
|


















<
<
<
<
<
<







24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53






54
55
56
57
58
59
60
|   Portions created by Jochen Loewer are Copyright (C) 1998, 1999
|   Jochen Loewer. All Rights Reserved.
|
|   Contributor(s):
|
|
|   $Log$
|   Revision 1.2  2002/02/23 01:13:33  rolf
|   Some code tweaking for a mostly warning free MS build
|
|   Revision 1.1.1.1  2002/02/22 01:05:35  rolf
|   tDOM0.7test with Jochens first set of patches
|
|
|
|   written by Jochen Loewer
|   April, 1999
|
\---------------------------------------------------------------------------*/



/*----------------------------------------------------------------------------
|   Includes
|
\---------------------------------------------------------------------------*/
#include <tcl.h>
#include <dom.h>
#include <tcldom.h>








/*
 *----------------------------------------------------------------------------
 *
 * Tdom_Init --
 *
 *	Initialization routine for loadable module
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    Tcl_CreateObjCommand (interp, "xml::parser", TclExpatObjCmd, NULL, NULL );
    Tcl_PkgProvide(interp, "expat", "2.0");      
#endif
    
    Tcl_PkgProvide (interp, "stackedtdom", "0.1");    
    Tcl_PkgProvide (interp, "tdom",  STR_TDOM_VERSION(TDOM_VERSION));

    /*
    fprintf(stderr, "sizeof(domNode)     = %d \n", sizeof(domNode) );
    fprintf(stderr, "sizeof(domTextNode) = %d \n", sizeof(domTextNode) );
    fprintf(stderr, "sizeof(domAttrNode) = %d \n", sizeof(domAttrNode) );
    */ 
    
    return TCL_OK;
}

int
Tdom_SafeInit (interp)
     Tcl_Interp *interp; /* Interpreter to initialise. */
{
    /* nothing special for safe interpreters -> just call Tdom_Init */
    return Tdom_Init (interp);
}







<
<
<
<
<
<










92
93
94
95
96
97
98






99
100
101
102
103
104
105
106
107
108
    Tcl_CreateObjCommand (interp, "xml::parser", TclExpatObjCmd, NULL, NULL );
    Tcl_PkgProvide(interp, "expat", "2.0");      
#endif
    
    Tcl_PkgProvide (interp, "stackedtdom", "0.1");    
    Tcl_PkgProvide (interp, "tdom",  STR_TDOM_VERSION(TDOM_VERSION));







    return TCL_OK;
}

int
Tdom_SafeInit (interp)
     Tcl_Interp *interp; /* Interpreter to initialise. */
{
    /* nothing special for safe interpreters -> just call Tdom_Init */
    return Tdom_Init (interp);
}
Changes to lib/tdom.tcl.
25
26
27
28
29
30
31







32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#   Jochen Loewer. All Rights Reserved.
#
#   Contributor(s):
#       Rolf Ade ([email protected]):   'fake' nodelists/live childNodes
#
#
#   $Log$







#   Revision 1.1  2002/02/22 01:05:35  rolf
#   Initial revision
#
#
#
#   written by Jochen Loewer
#   April, 1999
#
#----------------------------------------------------------------------------


package provide tdom 0.6


#----------------------------------------------------------------------------
#   setup namespaces for additional Tcl level methods, etc.
#
#----------------------------------------------------------------------------
namespace eval ::dom {







>
>
>
>
>
>
>
|
|









|







25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#   Jochen Loewer. All Rights Reserved.
#
#   Contributor(s):
#       Rolf Ade ([email protected]):   'fake' nodelists/live childNodes
#
#
#   $Log$
#   Revision 1.3  2002/02/28 00:39:00  rolf
#   Added tcl coded xpath function element-avaliable. Changed
#   function-avaliable accordingly.
#
#   Revision 1.2  2002/02/26 14:04:16  rolf
#   Updated the [package provide] to the new version number 0.7
#
#   Revision 1.1.1.1  2002/02/22 01:05:35  rolf
#   tDOM0.7test with Jochens first set of patches
#
#
#
#   written by Jochen Loewer
#   April, 1999
#
#----------------------------------------------------------------------------


package provide tdom 0.7


#----------------------------------------------------------------------------
#   setup namespaces for additional Tcl level methods, etc.
#
#----------------------------------------------------------------------------
namespace eval ::dom {
512
513
514
515
516
517
518

519
520
521
522
523
524
525
        boolean -
        ceiling -
        concat -
        contains -
        count -
        current -
        document -

        false -
        floor -
        generate-id -
        id -
        key -
        last -
        lang -







>







519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
        boolean -
        ceiling -
        concat -
        contains -
        count -
        current -
        document -
        element-avaliable -
        false -
        floor -
        generate-id -
        id -
        key -
        last -
        lang -
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561





562




















































563
564
565
566
567
568
569
        substring-before -
        sum -
        translate -
        true -
        unparsed-entity-uri {
            return [list bool true]
        }
        format-number -
        element-avaliable {
            return [list bool false]
        }
        default {
            set TclXpathFuncs [info procs ::dom::xpathFunc::*]
            if {[lsearch -exact $TclXpathFuncs $str] != -1} {
                return [list bool true]
            } else {
                return [list bool false]
            }
        }
    }
}

#----------------------------------------------------------------------------





#   functions-available




















































#
#----------------------------------------------------------------------------
proc ::dom::xpathFunc::system-property { ctxNode pos
                                         nodeListType nodeList args } {

    if {[llength $args] != 2} {
        error "system-property(): wrong # of args!"







|
<














>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







547
548
549
550
551
552
553
554

555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
        substring-before -
        sum -
        translate -
        true -
        unparsed-entity-uri {
            return [list bool true]
        }
        format-number {

            return [list bool false]
        }
        default {
            set TclXpathFuncs [info procs ::dom::xpathFunc::*]
            if {[lsearch -exact $TclXpathFuncs $str] != -1} {
                return [list bool true]
            } else {
                return [list bool false]
            }
        }
    }
}

#----------------------------------------------------------------------------
#   element-avaliable
#
#----------------------------------------------------------------------------
proc ::dom::xpathFunc::element-avaliable { ctxNode pos
                                            nodeListType nodeList args} {

    if {[llength $args] != 2} {
        error "element-avaliable(); wrong # of args!"
    }
    foreach { arg1Typ arg1Value } $args break
    set str [::dom::xpathFuncHelper::coerce2string $arg1Typ $arg1Value ]
    switch $str {
        stylesheet -
        transform -
        include -
        import -
        strip-space -
        preserve-space -
        template -
        apply-templates -
        apply-imports -
        call-template -
        element -
        attribute -
        attribute-set -
        text -
        processing-instruction -
        comment -
        copy -
        value-of -
        number -
        for-each -
        if -
        choose -
        when -
        otherwise -
        sort -
        variable -
        param -
        copy-of -
        with-param -
        key -
        message {
            return [list bool true]
        }
        decimal-format -
        output -
        namespace-alias -
        fallback -
        default {
            return [list bool false]
        }
    }
}


#----------------------------------------------------------------------------
#   system-property
#
#----------------------------------------------------------------------------
proc ::dom::xpathFunc::system-property { ctxNode pos
                                         nodeListType nodeList args } {

    if {[llength $args] != 2} {
        error "system-property(): wrong # of args!"
577
578
579
580
581
582
583
584
585
586
587
        xsl:vendor {
            return [list string "Jochen Loewer et. al. ([email protected])"]
        }
        xsl:vendor-url {
            return [list string "http://sdf.lonestar.org/~loewerj/tdom.cgi"]
        }
        default {
            return [string ""]
        }
    }
}







|



641
642
643
644
645
646
647
648
649
650
651
        xsl:vendor {
            return [list string "Jochen Loewer et. al. ([email protected])"]
        }
        xsl:vendor-url {
            return [list string "http://sdf.lonestar.org/~loewerj/tdom.cgi"]
        }
        default {
            return [list string ""]
        }
    }
}
Added tests/all.




























>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# expat.tcl --
#
# This scripts runs the tests using the expat parser.
#
# Copyright (c) 1999-2000 by Zveno Pty Ltd
# All rights reserved.
#
# $Id$

set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]

package require expat 2.0

source all.tcl
Added tests/all.tcl.
























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# all.tcl --
#
# This file contains a top-level script to run all of the Tcl
# tests.  Execute it by invoking "source all.test" when running tcltest
# in this directory.
#
# Copyright (c) 1998-1999 by Scriptics Corporation.
# All rights reserved.
# 
# RCS: @(#) $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}
set ::tcltest::testSingleFile false

puts stdout "Tcl $tcl_patchLevel tests running in interp:  [info nameofexecutable]"
puts stdout "Tests running in working dir:  $::tcltest::workingDir"
if {[llength $::tcltest::skip] > 0} {
    puts stdout "Skipping tests that match:  $::tcltest::skip"
}
if {[llength $::tcltest::match] > 0} {
    puts stdout "Only running tests that match:  $::tcltest::match"
}
source ../lib/tdom.tcl
# Use command line specified glob pattern (specified by -file or -f)
# if one exists.  Otherwise use *.test.  If given, the file pattern
# should be specified relative to the dir containing this file.  If no
# files are found to match the pattern, print an error message and exit.
set fileIndex [expr {[lsearch $argv "-file"] + 1}]
set fIndex [expr {[lsearch $argv "-f"] + 1}]
if {($fileIndex < 1) || ($fIndex > $fileIndex)} {
    set fileIndex $fIndex
}
if {$fileIndex > 0} {
    set globPattern [file join $::tcltest::testsDir [lindex $argv $fileIndex]]
    puts stdout "Sourcing files that match:  $globPattern"
} else {
    set globPattern [file join $::tcltest::testsDir *.test]
}
set fileList [glob -nocomplain $globPattern]
if {[llength $fileList] < 1} {
    puts "Error: no files found matching $globPattern"
    exit
}
set timeCmd {clock format [clock seconds]}
puts stdout "Tests began at [eval $timeCmd]"

# source each of the specified tests
foreach file [lsort $fileList] {
    set tail [file tail $file]
    if {[string match l.*.test $tail]} {
	# This is an SCCS lockfile; ignore it
	continue
    }
    puts stdout $tail
    if {[catch {source $file} msg]} {
	puts stdout $msg
    }
}

# cleanup
puts stdout "\nTests ended at [eval $timeCmd]"
::tcltest::cleanupTests 1
return











Added tests/attribute.test.


















































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# Features covered:  Attribute Lists
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on Attribute Lists.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1998-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

catch {unset result}
proc EStart {tagName attrList} {
    global result countAttributesOnly

    if {![llength $attrList] && !$countAttributesOnly} {
	if {[info exists result($tagName)]} {
	    set count 0
	    while {[info exists result($tagName/[incr count])]} {}
	    set result($tagName/$count) {}
	} else {
	    set result($tagName) {}
	}
	return {}
    }

    foreach {name value} $attrList {
	if {[info exists result($tagName,$name)]} {
	    set count 0
	    while {[info exists result($tagName,$name,[incr count])]} {}
	    set result($tagName,$name,$count) $value
	} else {
	    set result($tagName,$name) $value
	}
    }
}
catch {unset ::pcdata}
proc pcdata t {
    append ::pcdata $t
}

test attrList-1.1 {empty attribute list} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-1.1 {}}
    set parser [xml::parser attrList-1.1 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test></Test>
}
    array size result
} 0

test attrList-1.2 {single attribute} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-1.2 {}}
    set parser [xml::parser attrList-1.2 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr="1"></Test>
}

    array get result
} {Test,attr 1}

test attrList-1.3 {multiple distinct attributes} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-1.3 {}}
    set parser [xml::parser attrList-1.3 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test first="1" second='2'></Test>
}

    list [array size result] $result(Test,first) $result(Test,second)
} {2 1 2}

test attrList-1.4 {hyphen in attribute name} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-1.4 {}}
    set parser [xml::parser attrList-1.4 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test first-attr="1"></Test>
}

    array get result
} {Test,first-attr 1}

test attrList-2.1 {right angle bracket in attribute value} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-2.1 {}}
    set parser [xml::parser attrList-2.1 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr="value>"></Test>
}

    array get result
} {Test,attr value>}

test attrList-2.2 {right angle bracket in attribute value} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-2.2 {}}
    set parser [xml::parser attrList-2.2 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr="value1>value2"></Test>
}

    array get result
} {Test,attr value1>value2}

test attrList-2.3 {right angle bracket in attribute value} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-2.3 {}}
    set parser [xml::parser attrList-2.3 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr1="value1" attr2="value2>"></Test>
}

    array get result
} {Test,attr1 value1 Test,attr2 value2>}

test attrList-2.4 {right angle bracket in attribute value} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-2.4 {}}
    set parser [xml::parser attrList-2.4 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr2="value2>" attr1="value1"></Test>
}

    array get result
} {Test,attr1 value1 Test,attr2 value2>}

test attrList-2.5 {right angle brackets in attribute values} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-2.5 {}}
    set parser [xml::parser attrList-2.5 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr1="value>1" attr2="value>2"></Test>
}

    array get result
} {Test,attr1 value>1 Test,attr2 value>2}

test attrList-2.6 {right angle brackets in attribute values} {
    catch {unset ::result}
    catch {unset ::pcdata}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-2.6 {}}
    set parser [xml::parser attrList-2.6 \
	-elementstartcommand EStart \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr1="value>1">some text</Test>
}

    list [array get result] $::pcdata
} {{Test,attr1 value>1} {some text}}

test attrList-3.1 {unnested left brace in attribute value} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-3.1 {}}
    set parser [xml::parser attrList-3.1 \
	-elementstartcommand EStart]
    $parser parse [format {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr="%svalue"></Test>
} \{]

    array get result
} [list Test,attr [format {%svalue} \{]]

test attrList-3.2 {unnested right brace in attribute value} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-3.2 {}}
    set parser [xml::parser attrList-3.2 \
	-elementstartcommand EStart]
    $parser parse [format {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr="value%s"></Test>
} \}]

    array get result
} [list Test,attr [format {value%s} \}]]

test attrList-3.3 {Tcl special characters in attribute value} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-3.3 {}}
    set parser [xml::parser attrList-3.3 \
	-elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr="dollar $ backslash \ brackets [puts hello]"></Test>
}

    array get result
} {Test,attr {dollar $ backslash \ brackets [puts hello]}}

test attrList-4.1 {Unquoted attribute value} {
    catch {unset ::result}
    set ::countAttributesOnly 1

    catch {rename xml::attrList-4.1 {}}
    set parser [xml::parser attrList-4.1 \
	-elementstartcommand EStart]
    set retval [catch {
	$parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test attr=noquotes></Test>
}} msg]

    list $retval $msg
} [list 1 {error "not well-formed (invalid token)" at line 3 character 11}]

# Test case contributed by David Sutton <[email protected]>
test attrList-5.0 {Complicated attribute list} {
    catch {unset ::result}
    catch {unset ::pcdata}
    set ::countAttributesOnly 0

    catch {rename xml::attrList-5.0 {}}
    set parser [xml::parser attrList-5.0 \
	-elementstartcommand EStart \
	-characterdatacommand pcdata]
    set retval [catch {
	$parser parse {<?xml version="1.0"?>
<event name='LogAlarmReset' ID='22' startDisabled='no' deleteOnCompletion='no' startDateTime='' endDateTime=''>
  <stateChangeTrigger initialState='true' condition='AlarmSwitch = FALSE'/>
  <eventAction>LightState = LightCtl</eventAction>
  <eventAction>LOG(AlarmSwitch)</eventAction>
  <eventAction>DISABLE(BlinkLight)</eventAction>
  <eventAction>NOTIFY( AlarmSwitch,"Alarm has been reset")</eventAction>
</event>
}} msg]

    regsub -all "\[ \t\n\]+" $::pcdata { } ::pcdata
    set sortedResult {}
    foreach key [lsort -dictionary [array names ::result]] {
	lappend sortedResult $key $::result($key)
    }
    list $retval $sortedResult $::pcdata
} [list 0 {event,deleteOnCompletion no event,endDateTime {} event,ID 22 event,name LogAlarmReset event,startDateTime {} event,startDisabled no eventAction {} eventAction/1 {} eventAction/2 {} eventAction/3 {} stateChangeTrigger,condition {AlarmSwitch = FALSE} stateChangeTrigger,initialState true} { LightState = LightCtl LOG(AlarmSwitch) DISABLE(BlinkLight) NOTIFY( AlarmSwitch,"Alarm has been reset") }]

# Test case contributed by Marshall Rose <[email protected]>
test attrList-5.1 {Attribute list with quoted value} {
    catch {unset ::result}
    set ::countAttributesOnly 0

    catch {rename xml::attrList-5.1 {}}
    set parser [xml::parser attrList-5.1 \
	-elementstartcommand EStart]
    set retval [catch {
	$parser parse {<test example="isn&apos;t this legal?"/>}
    }]

    list $retval [array get ::result]
} {0 {test,example {isn't this legal?}}}

# cleanup
::tcltest::cleanupTests
return
Added tests/cdata.test.






























































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# Features covered:  CDATA sections
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on CDATA sections.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1998-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

catch {unset result}
proc pcdata data {
    append ::result $data
}
proc Estart {tagName attrList} {
    switch -- $tagName {
	Test {
	}
	default {
	    incr ::element
	}
    }
}

proc EStop tagname {
}

test cdata-1.1 {Simple CDATA section} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-1.1 {}}
    set parser [xml::parser cdata-1.1 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><![CDATA[This is CDATA]]></Test>
}
    list $::result $::element
} {{This is CDATA} 0}

test cdata-1.2 {CDATA test contributed by Richard Emberson ([email protected])} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-1.2 {}}
    set parser [xml::parser cdata-1.2 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
  <TOP>
    <![CDATA[928806871035]]>
  </TOP>
}
    list $::result $::element
} {{
    928806871035
  } 1}

# Test bug: ']]>' is not valid character data (XML Rec. subsect. 2.4) - 
# this should produce a warning.
test cdata-2.0 {CDATA section interpersed with comment} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-2.0 {}}
    set parser [xml::parser cdata-2.0 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><![CDATA[<!-- This is not a comment -->]]>
<!-- This is a comment <![CDATA[This is not CDATA]]>-->
<![CDATA[<!-- ]]>-->]]&gt;</Test>}
    list $::result $::element
} {{<!-- This is not a comment -->

<!-- -->]]>} 0}

test cdata-2.1 {CDATA section with an angle bracket} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-2.1 {}}
    set parser [xml::parser cdata-2.1 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><![CDATA[This is a > greater than sign]]></Test>
}
    list $::result $::element
} {{This is a > greater than sign} 0}

# Test case contributed by Marshall Rose ([email protected])
test cdata-2.2 {CDATA section with multiple angle brackets} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-2.2 {}}
    set parser [xml::parser cdata-2.2 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0" ?>
<!DOCTYPE Test>
<Test>
<artwork><![CDATA[
    <?xml version="1.0">
    <!DOCTYPE rfc SYSTEM "rfcXXXX.dtd">
    <rfc>
    ...

    </rfc>
]]></artwork>
</Test>}
    list $::result $::element
} {{

    <?xml version="1.0">
    <!DOCTYPE rfc SYSTEM "rfcXXXX.dtd">
    <rfc>
    ...

    </rfc>

} 1}

# Test case contributed by J. Linnenkohl ([email protected])
test cdata-2.3 {CDATA section with square brackets and curly braces} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-2.3 {}}
    set parser [xml::parser cdata-2.3 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0" ?>
<Tcl>
<![CDATA[
proc arithmetic_add {groups inputs outputs atts} {
    set ret_val ""
    set t "Hello World"
    set l [string length $t]
    return $ret_val
}
]]>
</Tcl>
}
    list $::result $::element
} {{

proc arithmetic_add {groups inputs outputs atts} {
    set ret_val ""
    set t "Hello World"
    set l [string length $t]
    return $ret_val
}

} 1}

test cdata-2.4 {CDATA section with angle brackets and curly braces} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-2.4 {}}
    set parser [xml::parser cdata-2.4 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0" ?>
<Tcl>
<![CDATA[
proc arithmetic_add {groups inputs outputs atts} {
    set ret_val [expr 1 > 2]
    set t "Hello World"
    set l [string length $t]
    return $ret_val
}
]]>
</Tcl>
}
    list $::result $::element
} {{

proc arithmetic_add {groups inputs outputs atts} {
    set ret_val [expr 1 > 2]
    set t "Hello World"
    set l [string length $t]
    return $ret_val
}

} 1}

test cdata-2.5 {CDATA section with angle brackets, Tcl specials trailing CDATA section} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-2.5 {}}
    set parser [xml::parser cdata-2.5 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0" ?>
<Tcl>
<![CDATA[
proc arithmetic_add {groups inputs outputs atts} {
    set ret_val [expr 1 > 2]
    set t "Hello World"
    set l [string length $t]
    return $ret_val
}
]]> that is {jolly} $good
</Tcl>
}
    list $::result $::element
} {{

proc arithmetic_add {groups inputs outputs atts} {
    set ret_val [expr 1 > 2]
    set t "Hello World"
    set l [string length $t]
    return $ret_val
}
 that is {jolly} $good
} 1}

# Test case contributed by Marshall Rose ([email protected])
test cdata-3.1 {CDATA section with PI and Tcl special characters} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-3.1 {}}
    set parser [xml::parser cdata-3.1 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
<?xml2rfc toc="yes"?>
<!DOCTYPE Test>
<Test>
<t>this is a \ test</t>
<artwork><![CDATA[
    <date month="December" year="1998"/>
]]></artwork>
</Test>}
    list $::result $::element
} {{
this is a \ test

    <date month="December" year="1998"/>

} 2}

test cdata-4.1 {CDATA section with entity reference} {
    set ::result {}
    set ::element 0

    catch {rename xml::cdata-4.1 {}}
    set parser [xml::parser cdata-4.1 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><![CDATA[no entity &lt;references&gt;]]></Test>}
    list $::result $::element
} {{no entity &lt;references&gt;} 0}


test cdata-5.1 {CDATA section whiteCDATAs} {
    set ::result {}
    set ::cdata {}

    catch {rename xml::cdata-5.1 {}}
    set parser [xml::parser cdata-5.1 \
            -ignorewhitecdata 1 \
            -characterdatacommand pcdata]
    $parser parse {<root>
<test>foo</test>
</root>}
    list $::result
} {foo}    

test cdata-5.2 {CDATA section whiteCDATAs} {
    set ::result {}
    set ::cdata {}

    catch {rename xml::cdata-5.2 {}}
    set parser [xml::parser cdata-5.2 \
            -characterdatacommand pcdata]
    $parser parse {<root> <test>foo</test> </root>}
    list $::result
} {{ foo }}    


# cleanup
::tcltest::cleanupTests
return
Added tests/comment.test.




















































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# Features covered:  comments
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on comments.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1998-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

catch {unset result}
proc pcdata data {
    append ::result $data
}
proc comment data {
    append ::comment $data
}
proc Estart {tagName attrList} {
    switch -- $tagName {
	test -
	Test {
	}
	default {
	    incr ::element
	}
    }
}

proc EStop tagname {
}

test comment-1.1 {Simple comment} {
    set ::result {}
    set ::comment {}
    set ::element 0

    catch {rename xml::comment-1.1 {}}
    set parser [xml::parser comment-1.1 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata \
	-commentcommand comment]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><!-- This is a comment --></Test>
}
    list $::comment $::result $::element
} {{ This is a comment } {} 0}

test comment-1.2 {Simple comment, no white space} {
    set ::result {}
    set ::comment {}
    set ::element 0

    catch {rename xml::comment-1.2 {}}
    set parser [xml::parser comment-1.2 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata \
	-commentcommand comment]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><!--This is a comment--></Test>
}
    list $::comment $::result $::element
} {{This is a comment} {} 0}

test comment-1.3 {Simple comment, within PCDATA} {
    set ::result {}
    set ::comment {}
    set ::element 0

    catch {rename xml::comment-1.3 {}}
    set parser [xml::parser comment-1.3 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata \
	-commentcommand comment]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test>surrounding <!--This is a comment--> PCDATA</Test>
}
    list $::comment $::result $::element
} {{This is a comment} {surrounding  PCDATA} 0}

test comment-1.3 {Simple comment, no white space} {
    set ::result {}
    set ::comment {}
    set ::element 0

    catch {rename xml::comment-1.3 {}}
    set parser [xml::parser comment-1.3 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata \
	-commentcommand comment]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><!--comment--></Test>
}
    list $::comment $::result $::element
} {comment {} 0}

test comment-1.4 {comment, with nested element} {
    set ::result {}
    set ::comment {}
    set ::element 0

    catch {rename xml::comment-1.4 {}}
    set parser [xml::parser comment-1.4 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata \
	-commentcommand comment]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><!-- comment <!blah>--></Test>
}
    list $::comment $::result $::element
} {{ comment <!blah>} {} 0}

test comment-2.1 {comment with an angle bracket} {
    set ::result {}
    set ::comment {}
    set ::element 0

    catch {rename xml::comment-2.1 {}}
    set parser [xml::parser comment-2.1 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata \
	-commentcommand comment]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><!-- This is a > greater than sign --></Test>
}
    list $::comment $::result $::element
} {{ This is a > greater than sign } {} 0}

test comment-2.2 {comment with multiple angle brackets} {
    set ::result {}
    set ::comment {}
    set ::element 0

    catch {rename xml::comment-2.2 {}}
    set parser [xml::parser comment-2.2 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata \
	-commentcommand comment]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><!-- 
  <Test>
    <Element>
      <Empty/>
    </Element>
  </Test>
 --></Test>
}
    list $::comment $::result $::element
} {{ 
  <Test>
    <Element>
      <Empty/>
    </Element>
  </Test>
 } {} 0}

set comment_2_3 [format {
    <question title="This is &lt;okay&gt;, right?" />
    <question title="Is &lt;this> bogus?" />
    <section title="This is a problem%s" />
  } \}]

test comment-2.3 {comment with entities} {
    set ::result {}
    set ::comment {}
    set ::element 0

    catch {rename xml::comment-2.3 {}}
    set parser [xml::parser comment-2.3 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata \
	-commentcommand comment]
    $parser parse "<?xml version='1.0'?>
<!DOCTYPE test SYSTEM 'test.dtd'>
<test>

<author>
<organization/>
</author>

<!--${comment_2_3}-->
</test>"

list [string compare $::comment ${comment_2_3}] [string trim $::result] $::element
} [list 0 {} 2]


# cleanup
::tcltest::cleanupTests
return
Added tests/data/REC-xslt-19991116.xml.






















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- $Id$ -->
<!DOCTYPE spec PUBLIC "-//W3C//DTD Specification V2.0//EN"
                      "/XML/1998/06/xmlspec-v20.dtd" [
<!ENTITY XML "http://www.w3.org/TR/REC-xml">
<!ENTITY XMLNames "http://www.w3.org/TR/REC-xml-names">
<!ENTITY XSLT.ns "http://www.w3.org/1999/XSL/Transform">
<!ENTITY XSLTA.ns "http://www.w3.org/1999/XSL/TransformAlias">
<!ENTITY XSLFO.ns "http://www.w3.org/1999/XSL/Format">
<!ENTITY XHTML.ns "http://www.w3.org/TR/xhtml1/strict">
<!ENTITY year "1999">
<!ENTITY month "November">
<!ENTITY MM "11">
<!ENTITY day "16">
<!ENTITY DD "16">
<!ENTITY YYYYMMDD "&year;&MM;&DD;">
<!ENTITY LEV "REC">
<!ENTITY XPath "http://www.w3.org/TR/xpath">
<!ATTLIST xfunction href CDATA "&XPath;">
<!-- DTD customizations -->
<!ELEMENT proto (arg*)>
<!ATTLIST proto
  name NMTOKEN #REQUIRED
  return-type (number|string|boolean|node-set|object) #REQUIRED
>
<!ELEMENT arg EMPTY>
<!ATTLIST arg
  type (number|string|boolean|node-set|object) #REQUIRED
  occur (opt|rep) #IMPLIED
>
<!ELEMENT function (#PCDATA)>
<!ELEMENT xfunction (#PCDATA)>
<!ATTLIST xfunction href CDATA #REQUIRED>
<!ELEMENT e:element-syntax
  (e:in-category*, e:attribute*, (e:empty|e:text|e:element|e:model|e:sequence|e:choice))
>
<!ATTLIST e:element-syntax
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
  name NMTOKEN #REQUIRED
>
<!ELEMENT e:in-category EMPTY>
<!ATTLIST
  e:in-category name NMTOKEN #REQUIRED
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:attribute (e:attribute-value-template|(e:constant|e:data-type)+)>
<!ATTLIST e:attribute
  name NMTOKEN #REQUIRED
  required (yes) #IMPLIED
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:attribute-value-template (e:constant|e:data-type)+>
<!ATTLIST e:attribute-value-template
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:constant EMPTY>
<!ATTLIST
  e:constant value CDATA #REQUIRED
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:data-type EMPTY>
<!ATTLIST e:data-type
  name NMTOKEN #REQUIRED
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:empty EMPTY>
<!ATTLIST e:empty
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:text EMPTY>
<!ATTLIST e:text
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:element EMPTY>
<!ATTLIST e:element
  name NMTOKEN #REQUIRED
  repeat (zero-or-one|zero-or-more|one-or-more) #IMPLIED
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:model EMPTY>
<!ATTLIST e:model
  name NMTOKEN #REQUIRED
  repeat (zero-or-one|zero-or-more|one-or-more) #IMPLIED
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:sequence (e:element|e:model|e:choice)+>
<!ATTLIST e:sequence
  repeat (zero-or-one|zero-or-more|one-or-more) #IMPLIED
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:choice (e:element|e:model|e:sequence)+>
<!ATTLIST e:choice
  repeat (zero-or-one|zero-or-more|one-or-more) #IMPLIED
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ELEMENT e:element-syntax-summary EMPTY>
<!ATTLIST e:element-syntax-summary 
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
<!ENTITY % local.illus.class "|proto|e:element-syntax|e:element-syntax-summary">
<!ENTITY % local.tech.class "|function|xfunction">
<!ENTITY % local.loc.class "|var">
<!ELEMENT var (#PCDATA)>
<!ATTLIST spec
  xmlns:e CDATA #FIXED "http://www.w3.org/1999/XSL/Spec/ElementSyntax"
>
]>
<spec xmlns:e="http://www.w3.org/1999/XSL/Spec/ElementSyntax">
<header>
<title>XSL Transformations (XSLT)</title>
<version>Version 1.0</version>
<w3c-designation>&LEV;-xslt-&YYYYMMDD;</w3c-designation>
<w3c-doctype>W3C Recommendation</w3c-doctype>
<pubdate><day>&day;</day><month>&month;</month><year>&year;</year></pubdate>
<publoc>
<loc href="http://www.w3.org/TR/&year;/&LEV;-xslt-&YYYYMMDD;"
          >http://www.w3.org/TR/&year;/&LEV;-xslt-&YYYYMMDD;</loc>
<loc role="available-format"
href="http://www.w3.org/TR/&year;/&LEV;-xslt-&YYYYMMDD;.xml">XML</loc>
<loc role="available-format"
href="http://www.w3.org/TR/&year;/&LEV;-xslt-&YYYYMMDD;.html">HTML</loc>
<!--
<loc href="http://www.w3.org/TR/&year;/&LEV;-xslt-&YYYYMMDD;.pdf"
          >http://www.w3.org/TR/&year;/&LEV;-xslt-&YYYYMMDD;.pdf</loc>
-->
</publoc>
<latestloc>
<loc href="http://www.w3.org/TR/xslt"
          >http://www.w3.org/TR/xslt</loc>
</latestloc>
<prevlocs>
<loc href="http://www.w3.org/TR/1999/PR-xslt-19991008"
          >http://www.w3.org/TR/1999/PR-xslt-19991008</loc>
<loc href="http://www.w3.org/1999/08/WD-xslt-19990813"
          >http://www.w3.org/1999/08/WD-xslt-19990813</loc>
<loc href="http://www.w3.org/1999/07/WD-xslt-19990709"
          >http://www.w3.org/1999/07/WD-xslt-19990709</loc>
<loc href="http://www.w3.org/TR/1999/WD-xslt-19990421"
          >http://www.w3.org/TR/1999/WD-xslt-19990421</loc>
<loc href="http://www.w3.org/TR/1998/WD-xsl-19981216"
          >http://www.w3.org/TR/1998/WD-xsl-19981216</loc>
<loc href="http://www.w3.org/TR/1998/WD-xsl-19980818"
          >http://www.w3.org/TR/1998/WD-xsl-19980818</loc>
</prevlocs>
<authlist>
<author>
<name>James Clark</name>
<email href="mailto:[email protected]">[email protected]</email>
</author>
</authlist>

<status>

<p>This document has been reviewed by W3C Members and other interested
parties and has been endorsed by the Director as a W3C <loc
href="http://www.w3.org/Consortium/Process/#RecsW3C">Recommendation</loc>. It
is a stable document and may be used as reference material or cited as
a normative reference from other documents. W3C's role in making the
Recommendation is to draw attention to the specification and to
promote its widespread deployment. This enhances the functionality and
interoperability of the Web.</p>

<p>The list of known errors in this specification is available at
<loc href="http://www.w3.org/&year;/&MM;/&LEV;-xslt-&YYYYMMDD;-errata"
>http://www.w3.org/&year;/&MM;/&LEV;-xslt-&YYYYMMDD;-errata</loc>.</p>

<p>Comments on this specification may be sent to <loc
href="mailto:[email protected]">[email protected]</loc>; <loc
href="http://lists.w3.org/Archives/Public/xsl-editors">archives</loc>
of the comments are available.  Public discussion of XSL, including
XSL Transformations, takes place on the <loc
href="http://www.mulberrytech.com/xsl/xsl-list/index.html">XSL-List</loc>
mailing list.</p>

<p>The English version of this specification is the only normative
version. However, for translations of this document, see <loc
href="http://www.w3.org/Style/XSL/translations.html"
>http://www.w3.org/Style/XSL/translations.html</loc>.</p>

<p>A list of current W3C Recommendations and other technical documents
can be found at <loc
href="http://www.w3.org/TR">http://www.w3.org/TR</loc>.</p>

<p>This specification has been produced as part of the <loc
href="http://www.w3.org/Style/Activity">W3C Style activity</loc>.</p>

</status>

<abstract>

<p>This specification defines the syntax and semantics of XSLT, which
is a language for transforming XML documents into other XML
documents.</p>

<p>XSLT is designed for use as part of XSL, which is a stylesheet
language for XML. In addition to XSLT, XSL includes an XML vocabulary
for specifying formatting.  XSL specifies the styling of an XML
document by using XSLT to describe how the document is transformed
into another XML document that uses the formatting vocabulary.</p>

<p>XSLT is also designed to be used independently of XSL.  However,
XSLT is not intended as a completely general-purpose XML
transformation language.  Rather it is designed primarily for the
kinds of transformations that are needed when XSLT is used as part of
XSL.</p>

</abstract>

<langusage>
<language id="EN">English</language>
<language id="ebnf">EBNF</language>
</langusage>
<revisiondesc>
<slist>
<sitem>See RCS log for revision history.</sitem>
</slist>
</revisiondesc>
</header>
<body>
<div1>
<head>Introduction</head>

<p>This specification defines the syntax and semantics of the XSLT
language.  A transformation in the XSLT language is expressed as a
well-formed XML document <bibref ref="XML"/> conforming to the
Namespaces in XML Recommendation <bibref ref="XMLNAMES"/>, which may
include both elements that are defined by XSLT and elements that are
not defined by XSLT.  <termdef id="dt-xslt-namespace" term="XSLT
Namespace">XSLT-defined elements are distinguished by belonging to a
specific XML namespace (see <specref ref="xslt-namespace"/>), which is
referred to in this specification as the <term>XSLT
namespace</term>.</termdef> Thus this specification is a definition of
the syntax and semantics of the XSLT namespace.</p>

<p>A transformation expressed in XSLT describes rules for transforming
a source tree into a result tree.  The transformation is achieved by
associating patterns with templates.  A pattern is matched against
elements in the source tree.  A template is instantiated to create
part of the result tree.  The result tree is separate from the source
tree.  The structure of the result tree can be completely different
from the structure of the source tree. In constructing the result
tree, elements from the source tree can be filtered and reordered, and
arbitrary structure can be added.</p>

<p>A transformation expressed in XSLT is called a stylesheet.  This is
because, in the case when XSLT is transforming into the XSL formatting
vocabulary, the transformation functions as a stylesheet.</p>

<p>This document does not specify how an XSLT stylesheet is associated
with an XML document.  It is recommended that XSL processors support
the mechanism described in <bibref ref="XMLSTYLE"/>.  When this or any
other mechanism yields a sequence of more than one XSLT stylesheet to
be applied simultaneously to a XML document, then the effect
should be the same as applying a single stylesheet that imports each
member of the sequence in order (see <specref ref="import"/>).</p>

<p>A stylesheet contains a set of template rules.  A template rule has
two parts: a pattern which is matched against nodes in the source tree
and a template which can be instantiated to form part of the result
tree.  This allows a stylesheet to be applicable to a wide class of
documents that have similar source tree structures.</p>

<p>A template is instantiated for a particular source element
to create part of the result tree. A template can contain elements
that specify literal result element structure.  A template can also
contain elements from the XSLT namespace
that are instructions for creating result tree
fragments.  When a template is instantiated, each instruction is
executed and replaced by the result tree fragment that it creates.
Instructions can select and process descendant source elements.  Processing a
descendant element creates a result tree fragment by finding the
applicable template rule and instantiating its template. Note
that elements are only processed when they have been selected by the
execution of an instruction.  The result tree is constructed by
finding the template rule for the root node and instantiating
its template.</p>

<p>In the process of finding the applicable template rule, more
than one template rule may have a pattern that matches a given
element. However, only one template rule will be applied. The
method for deciding which template rule to apply is described
in <specref ref="conflict"/>.</p>

<p>A single template by itself has considerable power: it can create
structures of arbitrary complexity; it can pull string values out of
arbitrary locations in the source tree; it can generate structures
that are repeated according to the occurrence of elements in the
source tree.  For simple transformations where the structure of the
result tree is independent of the structure of the source tree, a
stylesheet can often consist of only a single template, which
functions as a template for the complete result tree.  Transformations
on XML documents that represent data are often of this kind (see
<specref ref="data-example"/>). XSLT allows a simplified syntax for
such stylesheets (see <specref ref="result-element-stylesheet"/>).</p>

<p>When a template is instantiated, it is always instantiated with
respect to a <termdef id="dt-current-node" term="Current
Node"><term>current node</term></termdef> and a <termdef
id="dt-current-node-list" term="Current Node List"><term>current node
list</term></termdef>. The current node is always a member of the
current node list.  Many operations in XSLT are relative to the
current node. Only a few instructions change the current node list or
the current node (see <specref ref="rules"/> and <specref
ref="for-each"/>); during the instantiation of one of these
instructions, the current node list changes to a new list of nodes and
each member of this new list becomes the current node in turn; after
the instantiation of the instruction is complete, the current node and
current node list revert to what they were before the instruction was
instantiated.</p>

<p>XSLT makes use of the expression language defined by <bibref
ref="XPATH"/> for selecting elements for processing, for conditional
processing and for generating text.</p>

<p>XSLT provides two <quote>hooks</quote> for extending the language,
one hook for extending the set of instruction elements used in
templates and one hook for extending the set of functions used in
XPath expressions.  These hooks are both based on XML namespaces.
This version of XSLT does not define a mechanism for implementing the
hooks. See <specref ref="extension"/>.</p>

<note><p>The XSL WG intends to define such a mechanism in a future
version of this specification or in a separate
specification.</p></note>

<p>The element syntax summary notation used to describe the syntax of
XSLT-defined elements is described in <specref ref="notation"/>.</p>

<p>The MIME media types <code>text/xml</code> and
<code>application/xml</code> <bibref ref="RFC2376"/> should be used
for XSLT stylesheets.  It is possible that a media type will be
registered specifically for XSLT stylesheets; if and when it is, that
media type may also be used.</p>

</div1>

<div1>
<head>Stylesheet Structure</head>

<div2 id="xslt-namespace">
<head>XSLT Namespace</head>

<p>The XSLT namespace has the URI <code>&XSLT.ns;</code>.</p>

<note><p>The <code>1999</code> in the URI indicates the year in which
the URI was allocated by the W3C.  It does not indicate the version of
XSLT being used, which is specified by attributes (see <specref
ref="stylesheet-element"/> and <specref
ref="result-element-stylesheet"/>).</p></note>

<p>XSLT processors must use the XML namespaces mechanism <bibref
ref="XMLNAMES"/> to recognize elements and attributes from this
namespace. Elements from the XSLT namespace are recognized only in the
stylesheet not in the source document. The complete list of
XSLT-defined elements is specified in <specref
ref="element-syntax-summary"/>.  Vendors must not extend the XSLT
namespace with additional elements or attributes. Instead, any
extension must be in a separate namespace.  Any namespace that is used
for additional instruction elements must be identified by means of the
extension element mechanism specified in <specref
ref="extension-element"/>.</p>

<p>This specification uses a prefix of <code>xsl:</code> for referring
to elements in the XSLT namespace. However, XSLT stylesheets are free
to use any prefix, provided that there is a namespace declaration that
binds the prefix to the URI of the XSLT namespace.</p>

<p>An element from the XSLT namespace may have any attribute not from
the XSLT namespace, provided that the <xtermref
href="&XPath;#dt-expanded-name">expanded-name</xtermref> of the
attribute has a non-null namespace URI.  The presence of such
attributes must not change the behavior of XSLT elements and functions
defined in this document. Thus, an XSLT processor is always free to
ignore such attributes, and must ignore such attributes without giving
an error if it does not recognize the namespace URI. Such attributes
can provide, for example, unique identifiers, optimization hints, or
documentation.</p>

<p>It is an error for an element from the XSLT namespace to have
attributes with expanded-names that have null namespace URIs
(i.e. attributes with unprefixed names) other than attributes defined
for the element in this document.</p>

<note><p>The conventions used for the names of XSLT elements,
attributes and functions are that names are all lower-case, use
hyphens to separate words, and use abbreviations only if they already
appear in the syntax of a related language such as XML or
HTML.</p></note>


</div2>

<div2 id="stylesheet-element">
<head>Stylesheet Element</head>

<e:element-syntax name="stylesheet">
  <e:attribute name="id">
    <e:data-type name="id"/>
  </e:attribute>
  <e:attribute name="extension-element-prefixes">
    <e:data-type name="tokens"/>
  </e:attribute>
  <e:attribute name="exclude-result-prefixes">
    <e:data-type name="tokens"/>
  </e:attribute>
  <e:attribute name="version" required="yes">
    <e:data-type name="number"/>
  </e:attribute>
  <e:sequence>
    <e:element repeat="zero-or-more" name="import"/>
    <e:model name="top-level-elements"/>
  </e:sequence>
</e:element-syntax>

<e:element-syntax name="transform">
  <e:attribute name="id">
    <e:data-type name="id"/>
  </e:attribute>
  <e:attribute name="extension-element-prefixes">
    <e:data-type name="tokens"/>
  </e:attribute>
  <e:attribute name="exclude-result-prefixes">
    <e:data-type name="tokens"/>
  </e:attribute>
  <e:attribute name="version" required="yes">
    <e:data-type name="number"/>
  </e:attribute>
  <e:sequence>
    <e:element repeat="zero-or-more" name="import"/>
    <e:model name="top-level-elements"/>
  </e:sequence>
</e:element-syntax>

<p>A stylesheet is represented by an <code>xsl:stylesheet</code>
element in an XML document.  <code>xsl:transform</code> is allowed as
a synonym for <code>xsl:stylesheet</code>.</p>

<p>An <code>xsl:stylesheet</code> element must have a
<code>version</code> attribute, indicating the version of XSLT that
the stylesheet requires.  For this version of XSLT, the value should
be <code>1.0</code>.  When the value is not equal to <code>1.0</code>,
forwards-compatible processing mode is enabled (see <specref
ref="forwards"/>).</p>

<p>The <code>xsl:stylesheet</code> element may contain the following types
of elements:</p>
<ulist>
<item><p><code>xsl:import</code></p></item>
<item><p><code>xsl:include</code></p></item>
<item><p><code>xsl:strip-space</code></p></item>
<item><p><code>xsl:preserve-space</code></p></item>
<item><p><code>xsl:output</code></p></item>
<item><p><code>xsl:key</code></p></item>
<item><p><code>xsl:decimal-format</code></p></item>
<item><p><code>xsl:namespace-alias</code></p></item>
<item><p><code>xsl:attribute-set</code></p></item>
<item><p><code>xsl:variable</code></p></item>
<item><p><code>xsl:param</code></p></item>
<item><p><code>xsl:template</code></p></item>
</ulist>

<p><termdef id="dt-top-level" term="Top-level">An element occurring as
a child of an <code>xsl:stylesheet</code> element is called a
<term>top-level</term> element.</termdef></p>

<p>This example shows the structure of a stylesheet.  Ellipses
(<code>...</code>) indicate where attribute values or content have
been omitted.  Although this example shows one of each type of allowed
element, stylesheets may contain zero or more of each of these
elements.</p>

<eg>&lt;xsl:stylesheet version="1.0"
                xmlns:xsl="&XSLT.ns;"><![CDATA[
  <xsl:import href="..."/>

  <xsl:include href="..."/>

  <xsl:strip-space elements="..."/>
  
  <xsl:preserve-space elements="..."/>

  <xsl:output method="..."/>

  <xsl:key name="..." match="..." use="..."/>

  <xsl:decimal-format name="..."/>

  <xsl:namespace-alias stylesheet-prefix="..." result-prefix="..."/>

  <xsl:attribute-set name="...">
    ...
  </xsl:attribute-set>

  <xsl:variable name="...">...</xsl:variable>

  <xsl:param name="...">...</xsl:param>

  <xsl:template match="...">
    ...
  </xsl:template>

  <xsl:template name="...">
    ...
  </xsl:template>

</xsl:stylesheet>]]></eg>

<p>The order in which the children of the <code>xsl:stylesheet</code>
element occur is not significant except for <code>xsl:import</code>
elements and for error recovery.  Users are free to order the elements
as they prefer, and stylesheet creation tools need not provide control
over the order in which the elements occur.</p>

<p>In addition, the <code>xsl:stylesheet</code> element may contain
any element not from the XSLT namespace, provided that the
expanded-name of the element has a non-null namespace URI.  The presence of
such top-level elements must not change the behavior of XSLT elements
and functions defined in this document; for example, it would not be
permitted for such a top-level element to specify that
<code>xsl:apply-templates</code> was to use different rules to resolve
conflicts. Thus, an XSLT processor is always free to ignore such
top-level elements, and must ignore a top-level element without giving
an error if it does not recognize the namespace URI. Such elements can
provide, for example,</p>

<ulist>

<item><p>information used by extension elements or extension functions
(see <specref ref="extension"/>),</p></item>

<item><p>information about what to do with the result tree,</p></item>

<item><p>information about how to obtain the source tree,</p></item>

<item><p>metadata about the stylesheet,</p></item>

<item><p>structured documentation for the stylesheet.</p></item>

</ulist>

</div2>

<div2 id="result-element-stylesheet">
<head>Literal Result Element as Stylesheet</head>

<p>A simplified syntax is allowed for stylesheets that consist of only
a single template for the root node.  The stylesheet may consist of
just a literal result element (see <specref
ref="literal-result-element"/>).  Such a stylesheet is equivalent to a
stylesheet with an <code>xsl:stylesheet</code> element containing a
template rule containing the literal result element; the template rule
has a match pattern of <code>/</code>. For example</p>

<eg>&lt;html xsl:version="1.0"
      xmlns:xsl="&XSLT.ns;"
      xmlns="&XHTML.ns;"><![CDATA[
  <head>
    <title>Expense Report Summary</title>
  </head>
  <body>
    <p>Total Amount: <xsl:value-of select="expense-report/total"/></p>
  </body>
</html>]]></eg>

<p>has the same meaning as</p>

<eg>&lt;xsl:stylesheet version="1.0"
                xmlns:xsl="&XSLT.ns;"
                xmlns="&XHTML.ns;"><![CDATA[
<xsl:template match="/">
<html>
  <head>
    <title>Expense Report Summary</title>
  </head>
  <body>
    <p>Total Amount: <xsl:value-of select="expense-report/total"/></p>
  </body>
</html>
</xsl:template>
</xsl:stylesheet>]]></eg>

<p>A literal result element that is the document element of a
stylesheet must have an <code>xsl:version</code> attribute, which
indicates the version of XSLT that the stylesheet requires.  For this
version of XSLT, the value should be <code>1.0</code>; the value must
be a <xnt href="&XPath;#NT-Number">Number</xnt>.  Other literal result
elements may also have an <code>xsl:version</code> attribute. When the
<code>xsl:version</code> attribute is not equal to <code>1.0</code>,
forwards-compatible processing mode is enabled (see <specref
ref="forwards"/>).</p>

<p>The allowed content of a literal result element when used as a
stylesheet is no different from when it occurs within a
stylesheet. Thus, a literal result element used as a stylesheet cannot
contain <termref def="dt-top-level">top-level</termref> elements.</p>

<p>In some situations, the only way that a system can recognize that an
XML document needs to be processed by an XSLT processor as an XSLT
stylesheet is by examining the XML document itself.  Using the
simplified syntax makes this harder.</p>

<note><p>For example, another XML language (AXL) might also use an
<code>axl:version</code> on the document element to indicate that an
XML document was an AXL document that required processing by an AXL
processor; if a document had both an <code>axl:version</code>
attribute and an <code>xsl:version</code> attribute, it would be
unclear whether the document should be processed by an XSLT processor
or an AXL processor.</p></note>

<p>Therefore, the simplified syntax should not be used for XSLT
stylesheets that may be used in such a situation.  This situation can,
for example, arise when an XSLT stylesheet is transmitted as a message
with a MIME media type of <code>text/xml</code> or
<code>application/xml</code> to a recipient that will use the MIME
media type to determine how the message is processed.</p>

</div2>

<div2 id="qname">
<head>Qualified Names</head>

<p>The name of an internal XSLT object, specifically a named template
(see <specref ref="named-templates"/>), a mode (see <specref
ref="modes"/>), an attribute set (see <specref
ref="attribute-sets"/>), a key (see <specref ref="key"/>), a
decimal-format (see <specref ref="format-number"/>), a variable or a
parameter (see <specref ref="variables"/>) is specified as a <xnt
href="&XMLNames;#NT-QName">QName</xnt>.  If it has a prefix, then the
prefix is expanded into a URI reference using the namespace
declarations in effect on the attribute in which the name occurs.  The
<xtermref href="&XPath;#dt-expanded-name">expanded-name</xtermref>
consisting of the local part of the name and the possibly null URI
reference is used as the name of the object.  The default namespace is
<emph>not</emph> used for unprefixed names.</p>

</div2>

<div2 id="forwards">
<head>Forwards-Compatible Processing</head>

<p>An element enables forwards-compatible mode for itself, its
attributes, its descendants and their attributes if either it is an
<code>xsl:stylesheet</code> element whose <code>version</code>
attribute is not equal to <code>1.0</code>, or it is a literal result
element that has an <code>xsl:version</code> attribute whose value is
not equal to <code>1.0</code>, or it is a literal result element that
does not have an <code>xsl:version</code> attribute and that is the
document element of a stylesheet using the simplified syntax (see
<specref ref="result-element-stylesheet"/>).  A literal result element
that has an <code>xsl:version</code> attribute whose value is equal to
<code>1.0</code> disables forwards-compatible mode for itself, its
attributes, its descendants and their attributes.</p>

<p>If an element is processed in forwards-compatible mode, then:</p>

<ulist>

<item><p>if it is a <termref def="dt-top-level">top-level</termref>
element and XSLT 1.0 does not allow such elements as top-level
elements, then the element must be ignored along with its
content;</p></item>

<item><p>if it is an element in a template and XSLT 1.0 does not allow
such elements to occur in templates, then if the element is not
instantiated, an error must not be signaled, and if the element is
instantiated, the XSLT must perform fallback for the element as
specified in <specref ref="fallback"/>;</p></item>

<item><p>if the element has an attribute that XSLT 1.0 does not allow
the element to have or if the element has an optional attribute with a
value that the XSLT 1.0 does not allow the attribute to have, then the
attribute must be ignored.</p></item>

</ulist>

<p>Thus, any XSLT 1.0 processor must be able to process the following
stylesheet without error, although the stylesheet includes elements
from the XSLT namespace that are not defined in this
specification:</p>

<eg>&lt;xsl:stylesheet version="1.1"
                xmlns:xsl="&XSLT.ns;"><![CDATA[
  <xsl:template match="/">
    <xsl:choose>
      <xsl:when test="system-property('xsl:version') >= 1.1">
        <xsl:exciting-new-1.1-feature/>
      </xsl:when>
      <xsl:otherwise>
        <html>
        <head>
          <title>XSLT 1.1 required</title>
        </head>
        <body>
          <p>Sorry, this stylesheet requires XSLT 1.1.</p>
        </body>
        </html>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>]]></eg>

<note><p>If a stylesheet depends crucially on a top-level element
introduced by a version of XSL after 1.0, then the stylesheet can use
an <code>xsl:message</code> element with <code>terminate="yes"</code>
(see <specref ref="message"/>) to ensure that XSLT processors
implementing earlier versions of XSL will not silently ignore the
top-level element. For example,</p>

<eg>&lt;xsl:stylesheet version="1.5"
                xmlns:xsl="&XSLT.ns;"><![CDATA[

  <xsl:important-new-1.1-declaration/>

  <xsl:template match="/">
    <xsl:choose>
      <xsl:when test="system-property('xsl:version') &lt; 1.1">
        <xsl:message terminate="yes">
          <xsl:text>Sorry, this stylesheet requires XSLT 1.1.</xsl:text>
        </xsl:message>
      </xsl:when>
      <xsl:otherwise>
        ...
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  ...
</xsl:stylesheet>]]></eg>
</note>

<p>If an <termref def="dt-expression">expression</termref> occurs in
an attribute that is processed in forwards-compatible mode, then an
XSLT processor must recover from errors in the expression as
follows:</p>

<ulist>

<item><p>if the expression does not match the syntax allowed by the
XPath grammar, then an error must not be signaled unless the
expression is actually evaluated;</p></item>

<item><p>if the expression calls a function with an unprefixed name
that is not part of the XSLT library, then an error must not be
signaled unless the function is actually called;</p></item>

<item><p>if the expression calls a function with a number of arguments
that XSLT does not allow or with arguments of types that XSLT does not
allow, then an error must not be signaled unless the function is
actually called.</p></item>

</ulist>


</div2>

<div2>
<head>Combining Stylesheets</head>

<p>XSLT provides two mechanisms to combine stylesheets:</p>

<slist>

<sitem>an inclusion mechanism that allows stylesheets to be combined
without changing the semantics of the stylesheets being combined,
and</sitem>

<sitem>an import mechanism that allows stylesheets to override each
other.</sitem>

</slist>

<div3 id="include">
<head>Stylesheet Inclusion</head>

<e:element-syntax name="include">
  <e:in-category name="top-level-element"/>
  <e:attribute name="href" required="yes">
    <e:data-type name="uri-reference"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>An XSLT stylesheet may include another XSLT stylesheet using an
<code>xsl:include</code> element. The <code>xsl:include</code> element
has an <code>href</code> attribute whose value is a URI reference
identifying the stylesheet to be included.  A relative URI is resolved
relative to the base URI of the <code>xsl:include</code> element (see
<specref ref="base-uri"/>).</p>

<p>The <code>xsl:include</code> element is only allowed as a <termref
def="dt-top-level">top-level</termref> element.</p>

<p>The inclusion works at the XML tree level.  The resource located by
the <code>href</code> attribute value is parsed as an XML document,
and the children of the <code>xsl:stylesheet</code> element in this
document replace the <code>xsl:include</code> element in the including
document.  The fact that template rules or definitions are included
does not affect the way they are processed.</p>

<p>The included stylesheet may use the simplified syntax described in
<specref ref="result-element-stylesheet"/>.  The included stylesheet
is treated the same as the equivalent <code>xsl:stylesheet</code>
element.</p>

<p>It is an error if a stylesheet directly or indirectly includes
itself.</p>

<note><p>Including a stylesheet multiple times can cause errors
because of duplicate definitions.  Such multiple inclusions are less
obvious when they are indirect. For example, if stylesheet
<var>B</var> includes stylesheet <var>A</var>, stylesheet <var>C</var>
includes stylesheet <var>A</var>, and stylesheet <var>D</var> includes
both stylesheet <var>B</var> and stylesheet <var>C</var>, then
<var>A</var> will be included indirectly by <var>D</var> twice.  If
all of <var>B</var>, <var>C</var> and <var>D</var> are used as
independent stylesheets, then the error can be avoided by separating
everything in <var>B</var> other than the inclusion of <var>A</var>
into a separate stylesheet <var>B'</var> and changing <var>B</var> to
contain just inclusions of <var>B'</var> and <var>A</var>, similarly
for <var>C</var>, and then changing <var>D</var> to include
<var>A</var>, <var>B'</var>, <var>C'</var>.</p></note>

</div3>

<div3 id="import">
<head>Stylesheet Import</head>

<e:element-syntax name="import">
  <e:attribute name="href" required="yes">
    <e:data-type name="uri-reference"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>An XSLT stylesheet may import another XSLT stylesheet using an
<code>xsl:import</code> element.  Importing a stylesheet is the same
as including it (see <specref ref="include"/>) except that definitions
and template rules in the importing stylesheet take precedence over
template rules and definitions in the imported stylesheet; this is
described in more detail below.  The <code>xsl:import</code> element
has an <code>href</code> attribute whose value is a URI reference
identifying the stylesheet to be imported.  A relative URI is resolved
relative to the base URI of the <code>xsl:import</code> element (see
<specref ref="base-uri"/>).</p>

<p>The <code>xsl:import</code> element is only allowed as a <termref
def="dt-top-level">top-level</termref> element.  The
<code>xsl:import</code> element children must precede all other
element children of an <code>xsl:stylesheet</code> element, including
any <code>xsl:include</code> element children.  When
<code>xsl:include</code> is used to include a stylesheet, any
<code>xsl:import</code> elements in the included document are moved up
in the including document to after any existing
<code>xsl:import</code> elements in the including document.</p>

<p>For example,</p>

<eg>&lt;xsl:stylesheet version="1.0"
                xmlns:xsl="&XSLT.ns;"><![CDATA[
  <xsl:import href="article.xsl"/>
  <xsl:import href="bigfont.xsl"/>
  <xsl:attribute-set name="note-style">
    <xsl:attribute name="font-style">italic</xsl:attribute>
  </xsl:attribute-set>
</xsl:stylesheet>]]></eg>

<p><termdef id="dt-import-tree" term="Import Tree">The
<code>xsl:stylesheet</code> elements encountered during processing of
a stylesheet that contains <code>xsl:import</code> elements are
treated as forming an <term>import tree</term>.  In the import tree,
each <code>xsl:stylesheet</code> element has one import child for each
<code>xsl:import</code> element that it contains. Any
<code>xsl:include</code> elements are resolved before constructing the
import tree.</termdef> <termdef id="dt-import-precedence" term="Import
Precedence">An <code>xsl:stylesheet</code> element in the import tree
is defined to have lower <term>import precedence</term> than another
<code>xsl:stylesheet</code> element in the import tree if it would be
visited before that <code>xsl:stylesheet</code> element in a
post-order traversal of the import tree (i.e. a traversal of the
import tree in which an <code>xsl:stylesheet</code> element is visited
after its import children).</termdef> Each definition and template
rule has import precedence determined by the
<code>xsl:stylesheet</code> element that contains it.</p>

<p>For example, suppose</p>

<ulist>

<item><p>stylesheet <var>A</var> imports stylesheets <var>B</var>
and <var>C</var> in that order;</p></item>

<item><p>stylesheet <var>B</var> imports stylesheet
<var>D</var>;</p></item>

<item><p>stylesheet <var>C</var> imports stylesheet
<var>E</var>.</p></item>

</ulist>

<p>Then the order of import precedence (lowest first) is
<var>D</var>, <var>B</var>, <var>E</var>, <var>C</var>,
<var>A</var>.</p>

<note><p>Since <code>xsl:import</code> elements are required to occur
before any definitions or template rules, an implementation that
processes imported stylesheets at the point at which it encounters the
<code>xsl:import</code> element will encounter definitions and
template rules in increasing order of import precedence.</p></note>

<p>In general, a definition or template rule with higher import
precedence takes precedence over a definition or template rule with
lower import precedence.  This is defined in detail for each kind of
definition and for template rules.</p>

<p>It is an error if a stylesheet directly or indirectly imports
itself. Apart from this, the case where a stylesheet with a particular
URI is imported in multiple places is not treated specially. The
<termref def="dt-import-tree">import tree</termref> will have a
separate <code>xsl:stylesheet</code> for each place that it is
imported.</p>

<note><p>If <code>xsl:apply-imports</code> is used (see <specref
ref="apply-imports"/>), the behavior may be different from the
behavior if the stylesheet had been imported only at the place with
the highest <termref def="dt-import-precedence">import
precedence</termref>.</p></note>

</div3>

</div2>

<div2>
<head>Embedding Stylesheets</head>

<p>Normally an XSLT stylesheet is a complete XML document with the
<code>xsl:stylesheet</code> element as the document element. However,
an XSLT stylesheet may also be embedded in another resource. Two forms
of embedding are possible:</p>

<slist>

<sitem>the XSLT stylesheet may be textually embedded in a non-XML
resource, or</sitem>

<sitem>the <code>xsl:stylesheet</code> element may occur in an XML
document other than as the document element.</sitem>

</slist>

<p>To facilitate the second form of embedding, the
<code>xsl:stylesheet</code> element is allowed to have an ID attribute
that specifies a unique identifier.</p>

<note><p>In order for such an attribute to be used with the XPath
<xfunction>id</xfunction> function, it must actually be declared in
the DTD as being an ID.</p></note>

<p>The following example shows how the <code>xml-stylesheet</code>
processing instruction <bibref ref="XMLSTYLE"/> can be used to allow a
document to contain its own stylesheet.  The URI reference uses a
relative URI with a fragment identifier to locate the
<code>xsl:stylesheet</code> element:</p>

<eg><![CDATA[<?xml-stylesheet type="text/xml" href="#style1"?>
<!DOCTYPE doc SYSTEM "doc.dtd">
<doc>
<head>
<xsl:stylesheet id="style1"
                version="1.0"]]>
                xmlns:xsl="&XSLT.ns;"
                xmlns:fo="&XSLFO.ns;"><![CDATA[
<xsl:import href="doc.xsl"/>
<xsl:template match="id('foo')">
  <fo:block font-weight="bold"><xsl:apply-templates/></fo:block>
</xsl:template>
<xsl:template match="xsl:stylesheet">
  <!-- ignore -->
</xsl:template>
</xsl:stylesheet>
</head>
<body>
<para id="foo">
...
</para>
</body>
</doc>
]]></eg>

<note><p>A stylesheet that is embedded in the document to which it is
to be applied or that may be included or imported into an stylesheet
that is so embedded typically needs to contain a template rule that
specifies that <code>xsl:stylesheet</code> elements are to be
ignored.</p></note>

</div2>

</div1>

<div1 id="data-model">
<head>Data Model</head>

<p>The data model used by XSLT is the same as that used by <xspecref
href="&XPath;#data-model">XPath</xspecref> with the additions
described in this section.  XSLT operates on source, result and
stylesheet documents using the same data model.  Any two XML documents
that have the same tree will be treated the same by XSLT.</p>

<p>Processing instructions and comments in the stylesheet are ignored:
the stylesheet is treated as if neither processing instruction nodes
nor comment nodes were included in the tree that represents the
stylesheet.</p>

<div2 id="root-node-children">
<head>Root Node Children</head>

<p>The normal restrictions on the children of the root node are
relaxed for the result tree.  The result tree may have any sequence of
nodes as children that would be possible for an element node. In
particular, it may have text node children, and any number of element
node children. When written out using the XML output method (see
<specref ref="output"/>), it is possible that a result tree will not
be a well-formed XML document; however, it will always be a
well-formed external general parsed entity.</p>

<p>When the source tree is created by parsing a well-formed XML
document, the root node of the source tree will automatically satisfy
the normal restrictions of having no text node children and exactly
one element child.  When the source tree is created in some other way,
for example by using the DOM, the usual restrictions are relaxed for
the source tree as for the result tree.</p>

</div2>

<div2 id="base-uri">
<head>Base URI</head>

<p>Every node also has an associated URI called its base URI, which is
used for resolving attribute values that represent relative URIs into
absolute URIs.  If an element or processing instruction occurs in an
external entity, the base URI of that element or processing
instruction is the URI of the external entity; otherwise, the base URI
is the base URI of the document.  The base URI of the document node is
the URI of the document entity.  The base URI for a text node, a
comment node, an attribute node or a namespace node is the base URI of
the parent of the node.</p>

</div2>

<div2 id="unparsed-entities">
<head>Unparsed Entities</head>

<p>The root node has a mapping that gives the URI for each unparsed
entity declared in the document's DTD.  The URI is generated from the
system identifier and public identifier specified in the entity
declaration. The XSLT processor may use the public identifier to
generate a URI for the entity instead of the URI specified in the
system identifier.  If the XSLT processor does not use the public
identifier to generate the URI, it must use the system identifier; if
the system identifier is a relative URI, it must be resolved into an
absolute URI using the URI of the resource containing the entity
declaration as the base URI <bibref ref="RFC2396"/>.</p>

</div2>

<div2 id="strip">
<head>Whitespace Stripping</head>

<p>After the tree for a source document or stylesheet document has
been constructed, but before it is otherwise processed by XSLT,
some text nodes are stripped.  A text node is never stripped
unless it contains only whitespace characters.  Stripping the text
node removes the text node from the tree.  The stripping process takes
as input a set of element names for which whitespace must be
preserved.  The stripping process is applied to both stylesheets and
source documents, but the set of whitespace-preserving element names
is determined differently for stylesheets and for source
documents.</p>

<p>A text node is preserved if any of the following apply:</p>

<ulist>

<item><p>The element name of the parent of the text node is in the set
of whitespace-preserving element names.</p></item>

<item><p>The text node contains at least one non-whitespace character.
As in XML, a whitespace character is #x20, #x9, #xD or #xA.</p></item>

<item><p>An ancestor element of the text node has an
<code>xml:space</code> attribute with a value of
<code>preserve</code>, and no closer ancestor element has
<code>xml:space</code> with a value of
<code>default</code>.</p></item>

</ulist>

<p>Otherwise, the text node is stripped.</p>

<p>The <code>xml:space</code> attributes are not stripped from the
tree.</p>

<note><p>This implies that if an <code>xml:space</code> attribute is
specified on a literal result element, it will be included in the
result.</p></note>

<p>For stylesheets, the set of whitespace-preserving element names
consists of just <code>xsl:text</code>.</p>

<e:element-syntax name="strip-space">
  <e:in-category name="top-level-element"/>
  <e:attribute name="elements" required="yes">
    <e:data-type name="tokens"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<e:element-syntax name="preserve-space">
  <e:in-category name="top-level-element"/>
  <e:attribute name="elements" required="yes">
    <e:data-type name="tokens"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>For source documents, the set of whitespace-preserving element
names is specified by <code>xsl:strip-space</code> and
<code>xsl:preserve-space</code> <termref
def="dt-top-level">top-level</termref> elements.  These elements each
have an <code>elements</code> attribute whose value is a
whitespace-separated list of <xnt
href="&XPath;#NT-NameTest">NameTest</xnt>s.  Initially, the
set of whitespace-preserving element names contains all element names.
If an element name matches a <xnt
href="&XPath;#NT-NameTest">NameTest</xnt> in an
<code>xsl:strip-space</code> element, then it is removed from the set
of whitespace-preserving element names.  If an element name matches a
<xnt href="&XPath;#NT-NameTest">NameTest</xnt> in an
<code>xsl:preserve-space</code> element, then it is added to the set
of whitespace-preserving element names.  An element matches a <xnt
href="&XPath;#NT-NameTest">NameTest</xnt> if and only if the
<xnt href="&XPath;#NT-NameTest">NameTest</xnt> would be true
for the element as an <xspecref href="&XPath;#node-tests">XPath node
test</xspecref>.  Conflicts between matches to
<code>xsl:strip-space</code> and <code>xsl:preserve-space</code>
elements are resolved the same way as conflicts between template rules
(see <specref ref="conflict"/>).  Thus, the applicable match for a
particular element name is determined as follows:</p>

<ulist>

<item><p>First, any match with lower <termref
def="dt-import-precedence">import precedence</termref> than another
match is ignored.</p></item>

<item><p>Next, any match with a <xnt
href="&XPath;#NT-NameTest">NameTest</xnt> that has a lower
<termref def="dt-default-priority">default priority</termref> than the
<termref def="dt-default-priority">default priority</termref> of the
<xnt href="&XPath;#NT-NameTest">NameTest</xnt> of another
match is ignored.</p></item>

</ulist>

<p>It is an error if this leaves more than one match.  An XSLT
processor may signal the error; if it does not signal the error, it
must recover by choosing, from amongst the matches that are left, the
one that occurs last in the stylesheet.</p>

</div2>

</div1>

<div1>
<head>Expressions</head>

<p>XSLT uses the expression language defined by XPath <bibref
ref="XPATH"/>.  Expressions are used in XSLT for a variety of purposes
including:</p>

<slist>
<sitem>selecting nodes for processing;</sitem>
<sitem>specifying conditions for different ways of processing a node;</sitem>
<sitem>generating text to be inserted in the result tree.</sitem>
</slist>

<p><termdef id="dt-expression" term="Expression">An
<term>expression</term> must match the XPath production <xnt
href="&XPath;#NT-Expr">Expr</xnt>.</termdef></p>

<p>Expressions occur as the value of certain attributes on
XSLT-defined elements and within curly braces in <termref
def="dt-attribute-value-template">attribute value
template</termref>s.</p>

<p>In XSLT, an outermost expression (i.e. an expression that is not
part of another expression) gets its context as follows:</p>

<ulist>

<item><p>the context node comes from the <termref
def="dt-current-node">current node</termref></p></item>

<item><p>the context position comes from the position of the <termref
def="dt-current-node">current node</termref> in the <termref
def="dt-current-node-list">current node list</termref>; the first
position is 1</p></item>

<item><p>the context size comes from the size of the <termref
def="dt-current-node-list">current node list</termref></p></item>

<item><p>the variable bindings are the bindings in scope on the
element which has the attribute in which the expression occurs (see
<specref ref="variables"/>)</p></item>

<item><p>the set of namespace declarations are those in scope on the
element which has the attribute in which the expression occurs;
this includes the implicit declaration of the prefix <code>xml</code>
required by the the XML Namespaces Recommendation <bibref ref="XMLNAMES"/>;
the default
namespace (as declared by <code>xmlns</code>) is not part of this
set</p></item>

<item><p>the function library consists of the core function library
together with the additional functions defined in <specref
ref="add-func"/> and extension functions as described in <specref
ref="extension"/>; it is an error for an expression to include a call
to any other function</p></item>

</ulist>

</div1>

<div1 id="rules">
<head>Template Rules</head>

<div2>
<head>Processing Model</head>

<p>A list of source nodes is processed to create a result tree
fragment.  The result tree is constructed by processing a list
containing just the root node.  A list of source nodes is processed by
appending the result tree structure created by processing each of the
members of the list in order.  A node is processed by finding all the
template rules with patterns that match the node, and choosing the
best amongst them; the chosen rule's template is then instantiated
with the node as the <termref def="dt-current-node">current
node</termref> and with the list of source nodes as the <termref
def="dt-current-node-list">current node list</termref>.  A template
typically contains instructions that select an additional list of
source nodes for processing.  The process of matching, instantiation
and selection is continued recursively until no new source nodes are
selected for processing.</p>

<p>Implementations are free to process the source document in any way
that produces the same result as if it were processed using this
processing model.</p>

</div2>

<div2 id="patterns">
<head>Patterns</head>

<p><termdef id="dt-pattern" term="Pattern">Template rules identify the
nodes to which they apply by using a <term>pattern</term>.  As well as
being used in template rules, patterns are used for numbering (see
<specref ref="number"/>) and for declaring keys (see <specref
ref="key"/>).  A pattern specifies a set of conditions on a node.  A
node that satisfies the conditions matches the pattern; a node that
does not satisfy the conditions does not match the pattern.  The
syntax for patterns is a subset of the syntax for expressions. In
particular, location paths that meet certain restrictions can be used
as patterns.  An expression that is also a pattern always evaluates to
an object of type node-set.  A node matches a pattern if the node is a
member of the result of evaluating the pattern as an expression with
respect to some possible context; the possible contexts are those
whose context node is the node being matched or one of its
ancestors.</termdef></p>

<p>Here are some examples of patterns:</p>

<ulist>

<item><p><code>para</code> matches any <code>para</code> element</p></item>

<item><p><code>*</code> matches any element</p></item>

<item><p><code>chapter|appendix</code> matches any
<code>chapter</code> element and any <code>appendix</code>
element</p></item>

<item><p><code>olist/item</code> matches any <code>item</code> element with
an <code>olist</code> parent</p></item>

<item><p><code>appendix//para</code> matches any <code>para</code> element with
an <code>appendix</code> ancestor element</p></item>

<item><p><code>/</code> matches the root node</p></item>

<item><p><code>text()</code> matches any text node</p></item>

<item><p><code>processing-instruction()</code> matches any processing
instruction</p></item>

<item><p><code>node()</code> matches any node other than an attribute
node and the root node</p></item>

<item><p><code>id("W11")</code> matches the element with unique ID
<code>W11</code></p></item>

<item><p><code>para[1]</code> matches any <code>para</code> element
that is the first <code>para</code> child element of its
parent</p></item>

<item><p><code>*[position()=1 and self::para]</code> matches any
<code>para</code> element that is the first child element of its
parent</p></item>

<item><p><code>para[last()=1]</code> matches any <code>para</code>
element that is the only <code>para</code> child element of its
parent</p></item>

<item><p><code>items/item[position()>1]</code> matches any
<code>item</code> element that has a <code>items</code> parent and
that is not the first <code>item</code> child of its parent</p></item>

<item><p><code>item[position() mod 2 = 1]</code> would be true for any
<code>item</code> element that is an odd-numbered <code>item</code>
child of its parent.</p></item>

<item><p><code>div[@class="appendix"]//p</code> matches any
<code>p</code> element with a <code>div</code> ancestor element that
has a <code>class</code> attribute with value
<code>appendix</code></p></item>

<item><p><code>@class</code> matches any <code>class</code> attribute
(<emph>not</emph> any element that has a <code>class</code>
attribute)</p></item>

<item><p><code>@*</code> matches any attribute</p></item>

</ulist>

<p>A pattern must match the grammar for <nt
def="NT-Pattern">Pattern</nt>.  A <nt def="NT-Pattern">Pattern</nt> is
a set of location path patterns separated by <code>|</code>.  A
location path pattern is a location path whose steps all use only the
<code>child</code> or <code>attribute</code> axes.  Although patterns
must not use the <code>descendant-or-self</code> axis, patterns may
use the <code>//</code> operator as well as the <code>/</code>
operator.  Location path patterns can also start with an
<xfunction>id</xfunction> or <function>key</function> function call
with a literal argument.  Predicates in a pattern can use arbitrary
expressions just like predicates in a location path.</p>

<scrap>
<head>Patterns</head>
<prodgroup pcw5="1" pcw2="10">
<prod id="NT-Pattern">
<lhs>Pattern</lhs>
<rhs><nt def="NT-LocationPathPattern">LocationPathPattern</nt></rhs>
<rhs>| <nt def="NT-Pattern">Pattern</nt> '|' <nt def="NT-LocationPathPattern">LocationPathPattern</nt></rhs>
</prod>
<prod id="NT-LocationPathPattern">
<lhs>LocationPathPattern</lhs>
<rhs>'/' <nt def="NT-RelativePathPattern">RelativePathPattern</nt>?</rhs>
<rhs>| <nt def="NT-IdKeyPattern">IdKeyPattern</nt> (('/' | '//') <nt def="NT-RelativePathPattern">RelativePathPattern</nt>)?</rhs>
<rhs>| '//'? <nt def="NT-RelativePathPattern">RelativePathPattern</nt></rhs>
</prod>
<prod id="NT-IdKeyPattern">
<lhs>IdKeyPattern</lhs>
<rhs>'id' '(' <xnt href="&XPath;#NT-Literal">Literal</xnt> ')'</rhs>
<rhs>| 'key' '(' <xnt href="&XPath;#NT-Literal">Literal</xnt> ',' <xnt href="&XPath;#NT-Literal">Literal</xnt> ')'</rhs>
</prod>
<prod id="NT-RelativePathPattern">
<lhs>RelativePathPattern</lhs>
<rhs><nt def="NT-StepPattern">StepPattern</nt></rhs>
<rhs>| <nt def="NT-RelativePathPattern">RelativePathPattern</nt> '/' <nt def="NT-StepPattern">StepPattern</nt></rhs>
<rhs>| <nt def="NT-RelativePathPattern">RelativePathPattern</nt> '//' <nt def="NT-StepPattern">StepPattern</nt></rhs>
</prod>
<prod id="NT-StepPattern">
<lhs>StepPattern</lhs>
<rhs>
<nt def="NT-ChildOrAttributeAxisSpecifier">ChildOrAttributeAxisSpecifier</nt>
<xnt href="&XPath;#NT-NodeTest">NodeTest</xnt>
<xnt href="&XPath;#NT-Predicate">Predicate</xnt>*
</rhs>
</prod>
<prod id="NT-ChildOrAttributeAxisSpecifier">
<lhs>ChildOrAttributeAxisSpecifier</lhs>
<rhs><xnt href="&XPath;#NT-AbbreviatedAxisSpecifier">AbbreviatedAxisSpecifier</xnt></rhs>
<rhs>| ('child' | 'attribute') '::'</rhs>
</prod>
</prodgroup>
</scrap>

<p>A pattern is defined to match a node if and only if there is
possible context such that when the pattern is evaluated as an
expression with that context, the node is a member of the resulting
node-set.  When a node is being matched, the possible contexts have a
context node that is the node being matched or any ancestor of that
node, and a context node list containing just the context node.</p>

<p>For example, <code>p</code> matches any <code>p</code> element,
because for any <code>p</code> if the expression <code>p</code> is
evaluated with the parent of the <code>p</code> element as context the
resulting node-set will contain that <code>p</code> element as one of
its members.</p>

<note><p>This matches even a <code>p</code> element that is the
document element, since the document root is the parent of the
document element.</p></note>

<p>Although the semantics of patterns are specified indirectly in
terms of expression evaluation, it is easy to understand the meaning
of a pattern directly without thinking in terms of expression
evaluation.  In a pattern, <code>|</code> indicates alternatives; a
pattern with one or more <code>|</code> separated alternatives matches
if any one of the alternative matches.  A pattern that consists of a
sequence of <nt def="NT-StepPattern">StepPattern</nt>s separated by
<code>/</code> or <code>//</code> is matched from right to left.  The
pattern only matches if the rightmost <nt
def="NT-StepPattern">StepPattern</nt> matches and a suitable element
matches the rest of the pattern; if the separator is <code>/</code>
then only the parent is a suitable element; if the separator is
<code>//</code>, then any ancestor is a suitable element.  A <nt
def="NT-StepPattern">StepPattern</nt> that uses the child axis matches
if the <xnt href="&XPath;#NT-NodeTest">NodeTest</xnt> is true for the
node and the node is not an attribute node.  A <nt
def="NT-StepPattern">StepPattern</nt> that uses the attribute axis
matches if the <xnt href="&XPath;#NT-NodeTest">NodeTest</xnt> is true
for the node and the node is an attribute node.  When <code>[]</code>
is present, then the first <xnt
href="&XPath;#NT-PredicateExpr">PredicateExpr</xnt> in a <nt
def="NT-StepPattern">StepPattern</nt> is evaluated with the node being
matched as the context node and the siblings of the context node that
match the <xnt href="&XPath;#NT-NodeTest">NodeTest</xnt> as the
context node list, unless the node being matched is an attribute node,
in which case the context node list is all the attributes that have
the same parent as the attribute being matched and that match the <xnt
href="&XPath;#NT-NameTest">NameTest</xnt>.</p>

<p>For example</p>

<eg>appendix//ulist/item[position()=1]</eg>

<p>matches a node if and only if all of the following are true:</p>

<ulist>

<item><p>the <xnt href="&XPath;#NT-NodeTest">NodeTest</xnt> <code>item</code> is
true for the node and the node is not an attribute; in other words the
node is an <code>item</code> element</p></item>

<item><p>evaluating the <xnt href="&XPath;#NT-PredicateExpr">PredicateExpr</xnt>
<code>position()=1</code> with the node as context node and the
siblings of the node that are <code>item</code> elements as the
context node list yields true</p></item>

<item><p>the node has a parent that matches
<code>appendix//ulist</code>; this will be true if the parent is a
<code>ulist</code> element that has an <code>appendix</code> ancestor
element.</p></item>

</ulist>

</div2>

<div2>
<head>Defining Template Rules</head>

<e:element-syntax name="template">
  <e:in-category name="top-level-element"/>
  <e:attribute name="match">
    <e:data-type name="pattern"/>
  </e:attribute>
  <e:attribute name="name">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:attribute name="priority">
    <e:data-type name="number"/>
  </e:attribute>
  <e:attribute name="mode">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:sequence>
    <e:element repeat="zero-or-more" name="param"/>
    <e:model name="template"/>
  </e:sequence>
</e:element-syntax>

<p>A template rule is specified with the <code>xsl:template</code>
element. The <code>match</code> attribute is a <nt
def="NT-Pattern">Pattern</nt> that identifies the source node or nodes
to which the rule applies.  The <code>match</code> attribute is
required unless the <code>xsl:template</code> element has a
<code>name</code> attribute (see <specref ref="named-templates"/>).
It is an error for the value of the <code>match</code> attribute to
contain a <xnt
href="&XPath;#NT-VariableReference">VariableReference</xnt>. The
content of the <code>xsl:template</code> element is the template that
is instantiated when the template rule is applied.</p>

<p>For example, an XML document might contain:</p>

<eg><![CDATA[This is an <emph>important</emph> point.]]></eg>

<p>The following template rule matches <code>emph</code> elements and
produces a <code>fo:inline-sequence</code> formatting object with a
<code>font-weight</code> property of <code>bold</code>.</p>

<eg><![CDATA[<xsl:template match="emph">
  <fo:inline-sequence font-weight="bold">
    <xsl:apply-templates/>
  </fo:inline-sequence>
</xsl:template>
]]></eg>

<note><p>Examples in this document use the <code>fo:</code> prefix for
the namespace <code>&XSLFO.ns;</code>, which is
the namespace of the formatting objects defined in <bibref
ref="XSL"/>.</p></note>

<p>As described next, the <code>xsl:apply-templates</code> element
recursively processes the children of the source element.</p>

</div2>

<div2>
<head>Applying Template Rules</head>

<e:element-syntax name="apply-templates">
  <e:in-category name="instruction"/>
  <e:attribute name="select">
    <e:data-type name="node-set-expression"/>
  </e:attribute>
  <e:attribute name="mode">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:choice repeat="zero-or-more">
    <e:element name="sort"/>
    <e:element name="with-param"/>
  </e:choice>
</e:element-syntax>

<p>This example creates a block for a <code>chapter</code> element and
then processes its immediate children.</p>

<eg><![CDATA[<xsl:template match="chapter">
  <fo:block>
    <xsl:apply-templates/>
  </fo:block>
</xsl:template>]]></eg>

<p>In the absence of a <code>select</code> attribute, the
<code>xsl:apply-templates</code> instruction processes all of the
children of the current node, including text nodes.  However, text
nodes that have been stripped as specified in <specref ref="strip"/>
will not be processed.  If stripping of whitespace nodes has not been
enabled for an element, then all whitespace in the content of the
element will be processed as text, and thus whitespace
between child elements will count in determining the position of a
child element as returned by the <xfunction>position</xfunction>
function.</p>

<p>A <code>select</code> attribute can be used to process nodes
selected by an expression instead of processing all children.  The
value of the <code>select</code> attribute is an <termref
def="dt-expression">expression</termref>.  The expression must
evaluate to a node-set.  The selected set of nodes is processed in
document order, unless a sorting specification is present (see
<specref ref="sorting"/>).  The following example processes all of the
<code>author</code> children of the <code>author-group</code>:</p>

<eg><![CDATA[<xsl:template match="author-group">
  <fo:inline-sequence>
    <xsl:apply-templates select="author"/>
  </fo:inline-sequence>
</xsl:template>]]></eg>

<p>The following example processes all of the <code>given-name</code>s
of the <code>author</code>s that are children of
<code>author-group</code>:</p>

<eg><![CDATA[<xsl:template match="author-group">
  <fo:inline-sequence>
    <xsl:apply-templates select="author/given-name"/>
  </fo:inline-sequence>
</xsl:template>]]></eg>

<p>This example processes all of the <code>heading</code> descendant
elements of the <code>book</code> element.</p>

<eg><![CDATA[<xsl:template match="book">
  <fo:block>
    <xsl:apply-templates select=".//heading"/>
  </fo:block>
</xsl:template>]]></eg>

<p>It is also possible to process elements that are not descendants of
the current node.  This example assumes that a <code>department</code>
element has <code>group</code> children and <code>employee</code>
descendants. It finds an employee's department and then processes
the <code>group</code> children of the <code>department</code>.</p>

<eg><![CDATA[<xsl:template match="employee">
  <fo:block>
    Employee <xsl:apply-templates select="name"/> belongs to group
    <xsl:apply-templates select="ancestor::department/group"/>
  </fo:block>
</xsl:template>]]></eg>

<p>Multiple <code>xsl:apply-templates</code> elements can be used within a
single template to do simple reordering.  The following example
creates two HTML tables. The first table is filled with domestic sales
while the second table is filled with foreign sales.</p>

<eg><![CDATA[<xsl:template match="product">
  <table>
    <xsl:apply-templates select="sales/domestic"/>
  </table>
  <table>
    <xsl:apply-templates select="sales/foreign"/>
  </table>
</xsl:template>]]></eg>

<note>

<p>It is possible for there to be two matching descendants where one
is a descendant of the other.  This case is not treated specially:
both descendants will be processed as usual. For example, given a
source document</p>

<eg><![CDATA[<doc><div><div></div></div></doc>]]></eg>

<p>the rule</p>

<eg><![CDATA[<xsl:template match="doc">
  <xsl:apply-templates select=".//div"/>
</xsl:template>]]></eg>

<p>will process both the outer <code>div</code> and inner <code>div</code>
elements.</p>

</note>

<note><p>Typically, <code>xsl:apply-templates</code> is used to
process only nodes that are descendants of the current node.  Such use
of <code>xsl:apply-templates</code> cannot result in non-terminating
processing loops.  However, when <code>xsl:apply-templates</code> is
used to process elements that are not descendants of the current node,
the possibility arises of non-terminating loops. For example,</p>

<eg role="error"><![CDATA[<xsl:template match="foo">
  <xsl:apply-templates select="."/>
</xsl:template>]]></eg>

<p>Implementations may be able to detect such loops in some cases, but
the possibility exists that a stylesheet may enter a non-terminating
loop that an implementation is unable to detect. This may present a
denial of service security risk.</p></note>

</div2>

<div2 id="conflict">
<head>Conflict Resolution for Template Rules</head>

<p>It is possible for a source node to match more than one template
rule. The template rule to be used is determined as follows:</p>

<olist>

<item><p>First, all matching template rules that have lower <termref
def="dt-import-precedence">import precedence</termref> than the
matching template rule or rules with the highest import precedence are
eliminated from consideration.</p></item>

<item><p>Next, all matching template rules that have lower priority
than the matching template rule or rules with the highest priority are
eliminated from consideration.  The priority of a template rule is
specified by the <code>priority</code> attribute on the template rule.
The value of this must be a real number (positive or negative),
matching the production <xnt href="&XPath;#NT-Number">Number</xnt>
with an optional leading minus sign (<code>-</code>).  <termdef
id="dt-default-priority" term="Default Priority">The <term>default
priority</term> is computed as follows:</termdef></p>

<ulist>

<item><p>If the pattern contains multiple alternatives separated by
<code>|</code>, then it is treated equivalently to a set of template
rules, one for each alternative.</p></item>

<item><p>If the pattern has the form of a <xnt
href="&XMLNames;#NT-QName">QName</xnt> preceded by a <nt
def="NT-ChildOrAttributeAxisSpecifier">ChildOrAttributeAxisSpecifier</nt>
or has the form
<code>processing-instruction(</code><xnt href="&XPath;#NT-Literal"
>Literal</xnt><code>)</code> preceded by a <nt
def="NT-ChildOrAttributeAxisSpecifier">ChildOrAttributeAxisSpecifier</nt>,
then the priority is 0.</p></item>

<item><p>If the pattern has the form <xnt
href="&XMLNames;#NT-NCName">NCName</xnt><code>:*</code> preceded by a
<nt
def="NT-ChildOrAttributeAxisSpecifier">ChildOrAttributeAxisSpecifier</nt>,
then the priority is -0.25.</p></item>

<item><p>Otherwise, if the pattern consists of just a <xnt
href="&XPath;#NT-NodeTest">NodeTest</xnt> preceded by a <nt
def="NT-ChildOrAttributeAxisSpecifier">ChildOrAttributeAxisSpecifier</nt>,
then the priority is -0.5.</p></item>

<item><p>Otherwise, the priority is 0.5.</p></item>

</ulist>

<p>Thus, the most common kind of pattern (a pattern that tests for a
node with a particular type and a particular expanded-name) has
priority 0. The next less specific kind of pattern (a pattern that
tests for a node with a particular type and an expanded-name with a
particular namespace URI) has priority -0.25.  Patterns less specific
than this (patterns that just tests for nodes with particular types)
have priority -0.5.  Patterns more specific than the most common kind
of pattern have priority 0.5.</p>

</item>

</olist>

<p>It is an error if this leaves more than one matching template
rule.  An XSLT processor may signal the error; if it does not signal
the error, it must recover by choosing, from amongst the matching
template rules that are left, the one that occurs last in the
stylesheet.</p>

</div2>

<div2 id="apply-imports">
<head>Overriding Template Rules</head>

<e:element-syntax name="apply-imports">
  <e:in-category name="instruction"/>
  <e:empty/>
</e:element-syntax>

<p>A template rule that is being used to override a template rule in
an imported stylesheet (see <specref ref="conflict"/>) can use the
<code>xsl:apply-imports</code> element to invoke the overridden
template rule.</p>

<p><termdef id="dt-current-template-rule" term="Current Template
Rule">At any point in the processing of a stylesheet, there is a
<term>current template rule</term>.  Whenever a template rule is
chosen by matching a pattern, the template rule becomes the current
template rule for the instantiation of the rule's template. When an
<code>xsl:for-each</code> element is instantiated, the current
template rule becomes null for the instantiation of the content of the
<code>xsl:for-each</code> element.</termdef></p>

<p><code>xsl:apply-imports</code> processes the current node using
only template rules that were imported into the stylesheet element
containing the current template rule; the node is processed in the
current template rule's mode.  It is an error if
<code>xsl:apply-imports</code> is instantiated when the current
template rule is null.</p>

<p>For example, suppose the stylesheet <code>doc.xsl</code> contains a
template rule for <code>example</code> elements:</p>

<eg><![CDATA[<xsl:template match="example">
  <pre><xsl:apply-templates/></pre>
</xsl:template>]]></eg>

<p>Another stylesheet could import <code>doc.xsl</code> and modify the
treatment of <code>example</code> elements as follows:</p>

<eg><![CDATA[<xsl:import href="doc.xsl"/>

<xsl:template match="example">
  <div style="border: solid red">
     <xsl:apply-imports/>
  </div>
</xsl:template>]]></eg>

<p>The combined effect would be to transform an <code>example</code>
into an element of the form:</p>

<eg><![CDATA[<div style="border: solid red"><pre>...</pre></div>]]></eg>

</div2>

<div2 id="modes">
<head>Modes</head>

<p>Modes allow an element to be processed multiple times, each time
producing a different result.</p>

<p>Both <code>xsl:template</code> and <code>xsl:apply-templates</code>
have an optional <code>mode</code> attribute.  The value of the
<code>mode</code> attribute is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as described
in <specref ref="qname"/>. If <code>xsl:template</code> does not have
a <code>match</code> attribute, it must not have a <code>mode</code>
attribute.  If an <code>xsl:apply-templates</code> element has a
<code>mode</code> attribute, then it applies only to those template
rules from <code>xsl:template</code> elements that have a
<code>mode</code> attribute with the same value; if an
<code>xsl:apply-templates</code> element does not have a
<code>mode</code> attribute, then it applies only to those template
rules from <code>xsl:template</code> elements that do not have a
<code>mode</code> attribute.</p>

</div2>

<div2 id="built-in-rule">
<head>Built-in Template Rules</head>

<p>There is a built-in template rule to allow recursive processing to
continue in the absence of a successful pattern match by an explicit
template rule in the stylesheet.  This template rule applies to both
element nodes and the root node.  The following shows the equivalent
of the built-in template rule:</p>

<eg><![CDATA[<xsl:template match="*|/">
  <xsl:apply-templates/>
</xsl:template>]]></eg>

<p>There is also a built-in template rule for each mode, which allows
recursive processing to continue in the same mode in the absence of a
successful pattern match by an explicit template rule in the
stylesheet.  This template rule applies to both element nodes and the
root node.  The following shows the equivalent of the built-in
template rule for mode <code><var>m</var></code>.</p>

<eg>&lt;xsl:template match="*|/" mode="<var>m</var>">
  &lt;xsl:apply-templates mode="<var>m</var>"/>
&lt;/xsl:template></eg>

<p>There is also a built-in template rule for text and attribute nodes
that copies text through:</p>

<eg><![CDATA[<xsl:template match="text()|@*">
  <xsl:value-of select="."/>
</xsl:template>]]></eg>

<p>The built-in template rule for processing instructions and comments
is to do nothing.</p>

<eg><![CDATA[<xsl:template match="processing-instruction()|comment()"/>]]></eg>

<p>The built-in template rule for namespace nodes is also to do
nothing. There is no pattern that can match a namespace node; so, the
built-in template rule is the only template rule that is applied for
namespace nodes.</p>

<p>The built-in template rules are treated as if they were imported
implicitly before the stylesheet and so have lower <termref
def="dt-import-precedence">import precedence</termref> than all other
template rules.  Thus, the author can override a built-in template
rule by including an explicit template rule.</p>

</div2>


</div1>

<div1 id="named-templates">
<head>Named Templates</head>

<e:element-syntax name="call-template">
  <e:in-category name="instruction"/>
  <e:attribute name="name" required="yes">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:element repeat="zero-or-more" name="with-param"/>
</e:element-syntax>

<p>Templates can be invoked by name.  An <code>xsl:template</code>
element with a <code>name</code> attribute specifies a named template.
The value of the <code>name</code> attribute is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as described
in <specref ref="qname"/>. If an <code>xsl:template</code> element has
a <code>name</code> attribute, it may, but need not, also have a
<code>match</code> attribute.  An <code>xsl:call-template</code>
element invokes a template by name; it has a required
<code>name</code> attribute that identifies the template to be
invoked.  Unlike <code>xsl:apply-templates</code>,
<code>xsl:call-template</code> does not change the current node or the
current node list.</p>

<p>The <code>match</code>, <code>mode</code> and <code>priority</code> attributes on an
<code>xsl:template</code> element do not affect whether the template
is invoked by an <code>xsl:call-template</code> element.  Similarly,
the <code>name</code> attribute on an <code>xsl:template</code>
element does not affect whether the template is invoked by an
<code>xsl:apply-templates</code> element.</p>

<p>It is an error if a stylesheet contains more than one template with
the same name and same <termref def="dt-import-precedence">import
precedence</termref>.</p>

</div1>


<div1>
<head>Creating the Result Tree</head>

<p>This section describes instructions that directly create nodes in
the result tree.</p>

<div2>
<head>Creating Elements and Attributes</head>

<div3 id="literal-result-element">
<head>Literal Result Elements</head>

<p>In a template, an element in the stylesheet that does not belong to
the XSLT namespace and that is not an extension element (see <specref
ref="extension-element"/>) is instantiated to create an element node
with the same <xtermref
href="&XPath;#dt-expanded-name">expanded-name</xtermref>.  The content
of the element is a template, which is instantiated to give the
content of the created element node. The created element node will
have the attribute nodes that were present on the element node in the
stylesheet tree, other than attributes with names in the XSLT
namespace.</p>

<p>The created element node will also have a copy of the namespace
nodes that were present on the element node in the stylesheet tree
with the exception of any namespace node whose string-value is the
XSLT namespace URI (<code>&XSLT.ns;</code>), a
namespace URI declared as an extension namespace (see <specref
ref="extension-element"/>), or a namespace URI designated as an
excluded namespace.  A namespace URI is designated as an excluded
namespace by using an <code>exclude-result-prefixes</code> attribute
on an <code>xsl:stylesheet</code> element or an
<code>xsl:exclude-result-prefixes</code> attribute on a literal result
element.  The value of both these attributes is a whitespace-separated
list of namespace prefixes. The namespace bound to each of the
prefixes is designated as an excluded namespace.  It is an error if
there is no namespace bound to the prefix on the element bearing the
<code>exclude-result-prefixes</code> or
<code>xsl:exclude-result-prefixes</code> attribute.  The default
namespace (as declared by <code>xmlns</code>) may be designated as an
excluded namespace by including <code>#default</code> in the list of
namespace prefixes.  The designation of a namespace as an excluded
namespace is effective within the subtree of the stylesheet rooted at
the element bearing the <code>exclude-result-prefixes</code> or
<code>xsl:exclude-result-prefixes</code> attribute;
a subtree rooted at an <code>xsl:stylesheet</code> element
does not include any stylesheets imported or included by children
of that <code>xsl:stylesheet</code> element.</p>

<note><p>When a stylesheet uses a namespace declaration only for the
purposes of addressing the source tree, specifying the prefix in the
<code>exclude-result-prefixes</code> attribute will avoid superfluous
namespace declarations in the result tree.</p></note>

<p>The value of an attribute of a literal result element is
interpreted as an <termref def="dt-attribute-value-template">attribute
value template</termref>: it can contain expressions contained
in curly braces (<code>{}</code>).</p>

<p><termdef id="dt-literal-namespace-uri" term="Literal Namespace
URI">A namespace URI in the stylesheet tree that is being used to
specify a namespace URI in the result tree is called a <term>literal
namespace URI</term>.</termdef> This applies to:</p>

<ulist>

<item><p>the namespace URI in the expanded-name of a literal
result element in the stylesheet</p></item>

<item><p>the namespace URI in the expanded-name of an attribute
specified on a literal result element in the stylesheet</p></item>

<item><p>the string-value of a namespace node on a literal result
element in the stylesheet</p></item>

</ulist>

<e:element-syntax name="namespace-alias">
  <e:in-category name="top-level-element"/>
  <e:attribute name="stylesheet-prefix" required="yes">
    <e:data-type name="prefix"/>
    <e:constant value="#default"/>
  </e:attribute>
  <e:attribute name="result-prefix" required="yes">
    <e:data-type name="prefix"/>
    <e:constant value="#default"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p><termdef id="dt-alias" term="Alias">A stylesheet can use the
<code>xsl:namespace-alias</code> element to declare that one namespace
URI is an <term>alias</term> for another namespace URI.</termdef> When
a <termref def="dt-literal-namespace-uri">literal namespace
URI</termref> has been declared to be an alias for another namespace
URI, then the namespace URI in the result tree will be the namespace
URI that the literal namespace URI is an alias for, instead of the
literal namespace URI itself.  The <code>xsl:namespace-alias</code>
element declares that the namespace URI bound to the prefix specified
by the <code>stylesheet-prefix</code> attribute is an alias for the
namespace URI bound to the prefix specified by the
<code>result-prefix</code> attribute.  Thus, the
<code>stylesheet-prefix</code> attribute specifies the namespace URI
that will appear in the stylesheet, and the
<code>result-prefix</code> attribute specifies the corresponding
namespace URI that will appear in the result tree.  The default
namespace (as declared by <code>xmlns</code>) may be specified by
using <code>#default</code> instead of a prefix.  If a namespace URI
is declared to be an alias for multiple different namespace URIs, then
the declaration with the highest <termref
def="dt-import-precedence">import precedence</termref> is used. It is
an error if there is more than one such declaration.  An XSLT
processor may signal the error; if it does not signal the error, it
must recover by choosing, from amongst the declarations with the
highest import precedence, the one that occurs last in the
stylesheet.</p>

<p>When literal result elements are being used to create element,
attribute, or namespace nodes that use the XSLT namespace URI, the
stylesheet must use an alias.  For example, the stylesheet</p>

<eg>&lt;xsl:stylesheet
  version="1.0"
  xmlns:xsl="&XSLT.ns;"
  xmlns:fo="&XSLFO.ns;"
  xmlns:axsl="&XSLTA.ns;"><![CDATA[

<xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/>

<xsl:template match="/">
  <axsl:stylesheet>
    <xsl:apply-templates/>
  </axsl:stylesheet>
</xsl:template>

<xsl:template match="block">
  <axsl:template match="{.}">
     <fo:block><axsl:apply-templates/></fo:block>
  </axsl:template>
</xsl:template>

</xsl:stylesheet>]]></eg>

<p>will generate an XSLT stylesheet from a document of the form:</p>

<eg><![CDATA[<elements>
<block>p</block>
<block>h1</block>
<block>h2</block>
<block>h3</block>
<block>h4</block>
</elements>]]></eg>

<note><p>It may be necessary also to use aliases for namespaces other
than the XSLT namespace URI.  For example, literal result elements
belonging to a namespace dealing with digital signatures might cause
XSLT stylesheets to be mishandled by general-purpose security
software; using an alias for the namespace would avoid the possibility
of such mishandling.</p></note>

</div3>

<div3>
<head>Creating Elements with <code>xsl:element</code></head>

<e:element-syntax name="element">
  <e:in-category name="instruction"/>
  <e:attribute name="name" required="yes">
    <e:attribute-value-template>
      <e:data-type name="qname"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="namespace">
    <e:attribute-value-template>
      <e:data-type name="uri-reference"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="use-attribute-sets">
    <e:data-type name="qnames"/>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<p>The <code>xsl:element</code> element allows an element to be
created with a computed name.  The <xtermref
href="&XPath;#dt-expanded-name">expanded-name</xtermref> of the
element to be created is specified by a required <code>name</code>
attribute and an optional <code>namespace</code> attribute.  The
content of the <code>xsl:element</code> element is a template for the
attributes and children of the created element.</p>

<p>The <code>name</code> attribute is interpreted as an <termref
def="dt-attribute-value-template">attribute value template</termref>.
It is an error if the string that results from instantiating the
attribute value template is not a <xnt
href="&XMLNames;#NT-QName">QName</xnt>.  An XSLT processor may signal
the error; if it does not signal the error, then it must recover
by making the the result of instantiating the <code>xsl:element</code>
element be the sequence of nodes created by instantiating
the content of the  <code>xsl:element</code> element, excluding
any initial attribute nodes. If the <code>namespace</code> attribute is
not present then the <xnt href="&XMLNames;#NT-QName">QName</xnt> is
expanded into an expanded-name using the namespace declarations in
effect for the <code>xsl:element</code> element, including any default
namespace declaration.</p>

<p>If the <code>namespace</code> attribute is present, then it also is
interpreted as an <termref def="dt-attribute-value-template">attribute
value template</termref>. The string that results from instantiating
the attribute value template should be a URI reference.  It is not an
error if the string is not a syntactically legal URI reference.  If
the string is empty, then the expanded-name of the element has a null
namespace URI.  Otherwise, the string is used as the namespace URI of
the expanded-name of the element to be created. The local part of the
<xnt href="&XMLNames;#NT-QName">QName</xnt> specified by the
<code>name</code> attribute is used as the local part of the
expanded-name of the element to be created.</p>

<p>XSLT processors may make use of the prefix of the <xnt
href="&XMLNames;#NT-QName">QName</xnt> specified in the
<code>name</code> attribute when selecting the prefix used for
outputting the created element as XML; however, they are not required
to do so.</p>

</div3>

<div3 id="creating-attributes">
<head>Creating Attributes with <code>xsl:attribute</code></head>

<e:element-syntax name="attribute">
  <e:in-category name="instruction"/>
  <e:attribute name="name" required="yes">
    <e:attribute-value-template>
      <e:data-type name="qname"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="namespace">
    <e:attribute-value-template>
      <e:data-type name="uri-reference"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<p>The <code>xsl:attribute</code> element can be used to add
attributes to result elements whether created by literal result
elements in the stylesheet or by instructions such as
<code>xsl:element</code>. The <xtermref
href="&XPath;#dt-expanded-name">expanded-name</xtermref> of the
attribute to be created is specified by a required <code>name</code>
attribute and an optional <code>namespace</code> attribute.
Instantiating an <code>xsl:attribute</code> element adds an attribute
node to the containing result element node. The content of the
<code>xsl:attribute</code> element is a template for the value of the
created attribute.</p>

<p>The <code>name</code> attribute is interpreted as an <termref
def="dt-attribute-value-template">attribute value template</termref>.
It is an error if the string that results from instantiating the
attribute value template is not a <xnt
href="&XMLNames;#NT-QName">QName</xnt> or is the string
<code>xmlns</code>.  An XSLT processor may signal the error; if it
does not signal the error, it must recover by not adding the attribute
to the result tree. If the <code>namespace</code> attribute is not
present, then the <xnt href="&XMLNames;#NT-QName">QName</xnt> is
expanded into an expanded-name using the namespace declarations in
effect for the <code>xsl:attribute</code> element, <emph>not</emph>
including any default namespace declaration.</p>

<p>If the <code>namespace</code> attribute is present, then it also is
interpreted as an <termref def="dt-attribute-value-template">attribute
value template</termref>. The string that results from instantiating
it should be a URI reference.  It is not an error if the string is not
a syntactically legal URI reference.  If the string is empty, then the
expanded-name of the attribute has a null namespace URI.  Otherwise,
the string is used as the namespace URI of the expanded-name of the
attribute to be created. The local part of the <xnt
href="&XMLNames;#NT-QName">QName</xnt> specified by the
<code>name</code> attribute is used as the local part of the
expanded-name of the attribute to be created.</p>

<p>XSLT processors may make use of the prefix of the <xnt
href="&XMLNames;#NT-QName">QName</xnt> specified in the
<code>name</code> attribute when selecting the prefix used for
outputting the created attribute as XML; however, they are not
required to do so and, if the prefix is <code>xmlns</code>, they must
not do so. Thus, although it is not an error to do:</p>

<eg>&lt;xsl:attribute name="xmlns:xsl" namespace="whatever">&XSLT.ns;&lt;/xsl:attribute></eg>

<p>it will not result in a namespace declaration being output.</p>

<p>Adding an attribute to an element replaces any existing attribute
of that element with the same expanded-name.</p>

<p>The following are all errors:</p>

<ulist>

<item><p>Adding an attribute to an element after children have been
added to it; implementations may either signal the error or ignore the
attribute.</p></item>

<item><p>Adding an attribute to a node that is not an element;
implementations may either signal the error or ignore the
attribute.</p></item>

<item><p>Creating nodes other than text nodes during the
instantiation of the content of the <code>xsl:attribute</code>
element; implementations may either signal the error or ignore the
offending nodes.</p></item>

</ulist>

<note><p>When an <code>xsl:attribute</code> contains a text node with
a newline, then the XML output must contain a character reference.
For example,</p>

<eg><![CDATA[<xsl:attribute name="a">x
y</xsl:attribute>]]></eg>

<p>will result in the output</p>

<eg><![CDATA[a="x&#xA;y"]]></eg>

<p>(or with any equivalent character reference). The XML output cannot
be</p>

<eg><![CDATA[a="x
y"]]></eg>

<p>This is because XML 1.0 requires newline characters in attribute
values to be normalized into spaces but requires character references
to newline characters not to be normalized.  The attribute values in
the data model represent the attribute value after normalization.  If
a newline occurring in an attribute value in the tree were output as a
newline character rather than as character reference, then the
attribute value in the tree created by reparsing the XML would contain
a space not a newline, which would mean that the tree had not been
output correctly.</p></note>

</div3>

<div3 id="attribute-sets">

<head>Named Attribute Sets</head>

<e:element-syntax name="attribute-set">
  <e:in-category name="top-level-element"/>
  <e:attribute name="name" required="yes">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:attribute name="use-attribute-sets">
    <e:data-type name="qnames"/>
  </e:attribute>
  <e:element repeat="zero-or-more" name="attribute"/>
</e:element-syntax>

<p>The <code>xsl:attribute-set</code> element defines a named set of
attributes.  The <code>name</code> attribute specifies the name of the
attribute set.  The value of the <code>name</code> attribute is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as described
in <specref ref="qname"/>. The content of the <code>xsl:attribute-set</code>
element consists of zero or more <code>xsl:attribute</code> elements
that specify the attributes in the set.</p>

<p>Attribute sets are used by specifying a
<code>use-attribute-sets</code> attribute on <code>xsl:element</code>,
<code>xsl:copy</code> (see <specref ref="copying"/>) or
<code>xsl:attribute-set</code> elements.  The value of the
<code>use-attribute-sets</code> attribute is a whitespace-separated
list of names of attribute sets.  Each name is specified as a <xnt
href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as described
in <specref ref="qname"/>.  Specifying a
<code>use-attribute-sets</code> attribute is equivalent to adding
<code>xsl:attribute</code> elements for each of the attributes in each
of the named attribute sets to the beginning of the content of the
element with the <code>use-attribute-sets</code> attribute, in the
same order in which the names of the attribute sets are specified in
the <code>use-attribute-sets</code> attribute.  It is an error if use
of <code>use-attribute-sets</code> attributes on
<code>xsl:attribute-set</code> elements causes an attribute set to
directly or indirectly use itself.</p>

<p>Attribute sets can also be used by specifying an
<code>xsl:use-attribute-sets</code> attribute on a literal result
element.  The value of the <code>xsl:use-attribute-sets</code>
attribute is a whitespace-separated list of names of attribute sets.
The <code>xsl:use-attribute-sets</code> attribute has the same effect
as the <code>use-attribute-sets</code> attribute on
<code>xsl:element</code> with the additional rule that attributes
specified on the literal result element itself are treated as if they
were specified by <code>xsl:attribute</code> elements before any
actual <code>xsl:attribute</code> elements but after any
<code>xsl:attribute</code> elements implied by the
<code>xsl:use-attribute-sets</code> attribute.  Thus, for a literal
result element, attributes from attribute sets named in an
<code>xsl:use-attribute-sets</code> attribute will be added first, in
the order listed in the attribute; next, attributes specified on the
literal result element will be added; finally, any attributes
specified by <code>xsl:attribute</code> elements will be added.  Since
adding an attribute to an element replaces any existing attribute of
that element with the same name, this means that attributes specified
in attribute sets can be overridden by attributes specified on the
literal result element itself.</p>

<p>The template within each <code>xsl:attribute</code> element in an
<code>xsl:attribute-set</code> element is instantiated each time the
attribute set is used; it is instantiated using the same current node
and current node list as is used for instantiating the element bearing
the <code>use-attribute-sets</code> or
<code>xsl:use-attribute-sets</code> attribute. However, it is the
position in the stylesheet of the <code>xsl:attribute</code> element
rather than of the element bearing the <code>use-attribute-sets</code>
or <code>xsl:use-attribute-sets</code> attribute that determines which
variable bindings are visible (see <specref ref="variables"/>); thus,
only variables and parameters declared by <termref
def="dt-top-level">top-level</termref> <code>xsl:variable</code> and
<code>xsl:param</code> elements are visible.</p>

<p>The following example creates a named attribute set
<code>title-style</code> and uses it in a template rule.</p>

<eg><![CDATA[<xsl:template match="chapter/heading">
  <fo:block quadding="start" xsl:use-attribute-sets="title-style">
    <xsl:apply-templates/>
  </fo:block>
</xsl:template>

<xsl:attribute-set name="title-style">
  <xsl:attribute name="font-size">12pt</xsl:attribute>
  <xsl:attribute name="font-weight">bold</xsl:attribute>
</xsl:attribute-set>]]></eg>

<p>Multiple definitions of an attribute set with the same
expanded-name are merged.  An attribute from a definition that has
higher <termref def="dt-import-precedence">import precedence</termref>
takes precedence over an attribute from a definition that has lower
<termref def="dt-import-precedence">import precedence</termref>.  It
is an error if there are two attribute sets that have the same
expanded-name and equal import precedence and that both contain
the same attribute, unless there is a definition of the attribute set
with higher <termref def="dt-import-precedence">import
precedence</termref> that also contains the attribute.  An XSLT
processor may signal the error; if it does not signal the error, it
must recover by choosing from amongst the definitions that specify the
attribute that have the highest import precedence the one that was
specified last in the stylesheet.  Where the attributes in an
attribute set were specified is relevant only in merging the
attributes into the attribute set; it makes no difference when the
attribute set is used.</p>

</div3>

</div2>

<div2>

<head>Creating Text</head>

<p>A template can also contain text nodes.  Each text node in a
template remaining after whitespace has been stripped as specified in
<specref ref="strip"/> will create a text node with the same
string-value in the result tree.  Adjacent text nodes in the result
tree are automatically merged.</p>

<p>Note that text is processed at the tree level. Thus, markup of
<code>&amp;lt;</code> in a template will be represented in the
stylesheet tree by a text node that includes the character
<code>&lt;</code>. This will create a text node in the result tree
that contains a <code>&lt;</code> character, which will be represented
by the markup <code>&amp;lt;</code> (or an equivalent character
reference) when the result tree is externalized as an XML document
(unless output escaping is disabled as described in <specref
ref="disable-output-escaping"/>).</p>

<e:element-syntax name="text">
  <e:in-category name="instruction"/>
  <e:attribute name="disable-output-escaping">
    <e:constant value="yes"/>
    <e:constant value="no"/>
  </e:attribute>
  <e:text/>  
</e:element-syntax>

<p>Literal data characters may also be wrapped in an
<code>xsl:text</code> element.  This wrapping may change what
whitespace characters are stripped (see <specref ref="strip"/>) but
does not affect how the characters are handled by the XSLT processor
thereafter.</p>

<note><p>The <code>xml:lang</code> and <code>xml:space</code>
attributes are not treated specially by XSLT. In particular,</p>

<ulist>
<item><p>it is the responsibility of the stylesheet author explicitly
to generate any <code>xml:lang</code> or <code>xml:space</code>
attributes that are needed in the result;</p></item>

<item><p>specifying an <code>xml:lang</code> or <code>xml:space</code>
attribute on an element in the XSLT namespace will not cause any
<code>xml:lang</code> or <code>xml:space</code> attributes to appear
in the result.</p></item>
</ulist>
</note>

</div2>


<div2>
<head>Creating Processing Instructions</head>


<e:element-syntax name="processing-instruction">
  <e:in-category name="instruction"/>
  <e:attribute name="name" required="yes">
    <e:attribute-value-template>
      <e:data-type name="ncname"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<p>The <code>xsl:processing-instruction</code> element is instantiated
to create a processing instruction node.  The content of the
<code>xsl:processing-instruction</code> element is a template for the
string-value of the processing instruction node.  The
<code>xsl:processing-instruction</code> element has a required
<code>name</code> attribute that specifies the name of the processing
instruction node.  The value of the <code>name</code> attribute is
interpreted as an <termref def="dt-attribute-value-template">attribute
value template</termref>.</p>

<p>For example, this</p>

<eg><![CDATA[<xsl:processing-instruction name="xml-stylesheet">href="book.css" type="text/css"</xsl:processing-instruction>]]></eg>

<p>would create the processing instruction</p>

<eg><![CDATA[<?xml-stylesheet href="book.css" type="text/css"?>]]></eg>

<p>It is an error if the string that results from instantiating the
<code>name</code> attribute is not both an <xnt
href="&XMLNames;#NT-NCName">NCName</xnt> and a <xnt
href="&XML;#NT-PITarget">PITarget</xnt>.  An XSLT processor may signal
the error; if it does not signal the error, it must recover by not
adding the processing instruction to the result tree.</p>

<note><p>This means that <code>xsl:processing-instruction</code>
cannot be used to output an XML declaration.  The
<code>xsl:output</code> element should be used instead (see <specref
ref="output"/>).</p></note>

<p>It is an error if instantiating the content of
<code>xsl:processing-instruction</code> creates nodes other than
text nodes.  An XSLT processor may signal the error; if it does not
signal the error, it must recover by ignoring the offending nodes
together with their content.</p>

<p>It is an error if the result of instantiating the content of the
<code>xsl:processing-instruction</code> contains the string
<code>?&gt;</code>.  An XSLT processor may signal the error; if it does
not signal the error, it must recover by inserting a space after any
occurrence of <code>?</code> that is followed by a <code>&gt;</code>.</p>

</div2>

<div2>
<head>Creating Comments</head>

<e:element-syntax name="comment">
  <e:in-category name="instruction"/>
  <e:model name="template"/>
</e:element-syntax>

<p>The <code>xsl:comment</code> element is instantiated to create a
comment node in the result tree.  The content of the
<code>xsl:comment</code> element is a template for the string-value of
the comment node.</p>

<p>For example, this</p>

<eg><![CDATA[<xsl:comment>This file is automatically generated. Do not edit!</xsl:comment>]]></eg>

<p>would create the comment</p>

<eg><![CDATA[<!--This file is automatically generated. Do not edit!-->]]></eg>

<p>It is an error if instantiating the content of
<code>xsl:comment</code> creates nodes other than text nodes.  An
XSLT processor may signal the error; if it does not signal the error,
it must recover by ignoring the offending nodes together with their
content.</p>

<p>It is an error if the result of instantiating the content of the
<code>xsl:comment</code> contains the string <code>--</code> or ends
with <code>-</code>.  An XSLT processor may signal the error; if it
does not signal the error, it must recover by inserting a space after
any occurrence of <code>-</code> that is followed by another
<code>-</code> or that ends the comment.</p>

</div2>

<div2 id="copying">
<head>Copying</head>

<e:element-syntax name="copy">
  <e:in-category name="instruction"/>
  <e:attribute name="use-attribute-sets">
    <e:data-type name="qnames"/>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<p>The <code>xsl:copy</code> element provides an easy way of copying
the current node. Instantiating the <code>xsl:copy</code> element
creates a copy of the current node.  The namespace nodes of the
current node are automatically copied as well, but the attributes and
children of the node are not automatically copied.  The content of the
<code>xsl:copy</code> element is a template for the attributes and
children of the created node; the content is instantiated only for
nodes of types that can have attributes or children (i.e. root
nodes and element nodes).</p>

<p>The <code>xsl:copy</code> element may have a
<code>use-attribute-sets</code> attribute (see <specref
ref="attribute-sets"/>). This is used only when copying element
nodes.</p>

<p>The root node is treated specially because the root node of the
result tree is created implicitly.  When the current node is the root
node, <code>xsl:copy</code> will not create a root node, but will just
use the content template.</p>

<p>For example, the identity transformation can be written using
<code>xsl:copy</code> as follows:</p>

<eg><![CDATA[<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>]]></eg>

<p>When the current node is an attribute, then if it would be an error
to use <code>xsl:attribute</code> to create an attribute with the same
name as the current node, then it is also an error to use
<code>xsl:copy</code> (see <specref ref="creating-attributes"/>).</p>

<p>The following example shows how <code>xml:lang</code> attributes
can be easily copied through from source to result. If a stylesheet
defines the following named template:</p>

<eg><![CDATA[<xsl:template name="apply-templates-copy-lang">
 <xsl:for-each select="@xml:lang">
   <xsl:copy/>
 </xsl:for-each>
 <xsl:apply-templates/>
</xsl:template>]]></eg>

<p>then it can simply do</p>

<eg><![CDATA[<xsl:call-template name="apply-templates-copy-lang"/>]]></eg>

<p>instead of</p>

<eg><![CDATA[<xsl:apply-templates/>]]></eg>

<p>when it wants to copy the <code>xml:lang</code> attribute.</p>

</div2>

<div2>
<head>Computing Generated Text</head>

<p>Within a template, the <code>xsl:value-of</code> element can be
used to compute generated text, for example by extracting text from
the source tree or by inserting the value of a variable.  The
<code>xsl:value-of</code> element does this with an <termref
def="dt-expression">expression</termref> that is specified as the
value of the <code>select</code> attribute.  Expressions can
also be used inside attribute values of literal result elements by
enclosing the expression in curly braces (<code>{}</code>).</p>

<div3 id="value-of">
<head>Generating Text with <code>xsl:value-of</code></head>

<e:element-syntax name="value-of">
  <e:in-category name="instruction"/>
  <e:attribute name="select" required="yes">
    <e:data-type name="string-expression"/>
  </e:attribute>
  <e:attribute name="disable-output-escaping">
    <e:constant value="yes"/>
    <e:constant value="no"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>The <code>xsl:value-of</code> element is instantiated to create a
text node in the result tree.  The required <code>select</code>
attribute is an <termref def="dt-expression">expression</termref>;
this expression is evaluated and the resulting object is converted to
a string as if by a call to the <xfunction>string</xfunction>
function. The string specifies the string-value of the created text
node.  If the string is empty, no text node will be created.  The
created text node will be merged with any adjacent text nodes.</p>

<p>The <code>xsl:copy-of</code> element can be used to copy a node-set
over to the result tree without converting it to a string. See <specref
ref="copy-of"/>.</p>

<p>For example, the following creates an HTML paragraph from a
<code>person</code> element with <code>given-name</code> and
<code>family-name</code> attributes.  The paragraph will contain the value
of the <code>given-name</code> attribute of the current node followed
by a space and the value of the <code>family-name</code> attribute of the
current node.</p>

<eg><![CDATA[<xsl:template match="person">
  <p>
   <xsl:value-of select="@given-name"/>
   <xsl:text> </xsl:text>
   <xsl:value-of select="@family-name"/>
  </p>
</xsl:template>]]></eg>

<p>For another example, the following creates an HTML paragraph from a
<code>person</code> element with <code>given-name</code> and
<code>family-name</code> children elements.  The paragraph will
contain the string-value of the first <code>given-name</code> child
element of the current node followed by a space and the string-value
of the first <code>family-name</code> child element of the current
node.</p>

<eg><![CDATA[<xsl:template match="person">
  <p>
   <xsl:value-of select="given-name"/>
   <xsl:text> </xsl:text>
   <xsl:value-of select="family-name"/>
  </p>
</xsl:template>]]></eg>

<p>The following precedes each <code>procedure</code> element with a
paragraph containing the security level of the procedure.  It assumes
that the security level that applies to a procedure is determined by a
<code>security</code> attribute on the procedure element or on an
ancestor element of the procedure. It also assumes that if more than
one such element has a <code>security</code> attribute then the
security level is determined by the element that is closest to the
procedure.</p>

<eg><![CDATA[<xsl:template match="procedure">
  <fo:block>
    <xsl:value-of select="ancestor-or-self::*[@security][1]/@security"/>
  </fo:block>
  <xsl:apply-templates/>
</xsl:template>]]></eg>

</div3>

<div3 id="attribute-value-templates">
<head>Attribute Value Templates</head>

<p><termdef id="dt-attribute-value-template" term="Attribute Value
Template">In an attribute value that is interpreted as an
<term>attribute value template</term>, such as an attribute of a
literal result element, an <termref
def="dt-expression">expression</termref> can be used by surrounding
the expression with curly braces (<code>{}</code>)</termdef>.  The
attribute value template is instantiated by replacing the expression
together with surrounding curly braces by the result of evaluating the
expression and converting the resulting object to a string as if by a
call to the <xfunction>string</xfunction> function.  Curly braces are
not recognized in an attribute value in an XSLT stylesheet unless the
attribute is specifically stated to be one that is interpreted as an
attribute value template; in an element syntax summary, the value
of such attributes is surrounded by curly braces.</p>

<note><p>Not all attributes are interpreted as attribute value
templates.  Attributes whose value is an expression or pattern,
attributes of <termref def="dt-top-level">top-level</termref> elements
and attributes that refer to named XSLT objects are not interpreted as
attribute value templates. In addition, <code>xmlns</code> attributes
are not interpreted as attribute value templates; it would not be
conformant with the XML Namespaces Recommendation to do
this.</p></note>

<p>The following example creates an <code>img</code> result element
from a <code>photograph</code> element in the source; the value of the
<code>src</code> attribute of the <code>img</code> element is computed
from the value of the <code>image-dir</code> variable and the
string-value of the <code>href</code> child of the
<code>photograph</code> element; the value of the <code>width</code>
attribute of the <code>img</code> element is computed from the value
of the <code>width</code> attribute of the <code>size</code> child of
the <code>photograph</code> element:</p>

<eg><![CDATA[<xsl:variable name="image-dir">/images</xsl:variable>

<xsl:template match="photograph">
<img src="{$image-dir}/{href}" width="{size/@width}"/>
</xsl:template>]]></eg>

<p>With this source</p>

<eg><![CDATA[<photograph>
  <href>headquarters.jpg</href>
  <size width="300"/>
</photograph>]]></eg>

<p>the result would be</p>

<eg><![CDATA[<img src="/images/headquarters.jpg" width="300"/>]]></eg>

<p>When an attribute value template is instantiated, a double left or
right curly brace outside an expression will be replaced by a single
curly brace.  It is an error if a right curly brace occurs in an
attribute value template outside an expression without being followed
by a second right curly brace.  A right curly brace inside a <xnt
href="&XPath;#NT-Literal">Literal</xnt> in an expression is not
recognized as terminating the expression.</p>

<p>Curly braces are <emph>not</emph> recognized recursively inside
expressions.  For example:</p>

<eg role="error"><![CDATA[<a href="#{id({@ref})/title}">]]></eg>

<p>is <emph>not</emph> allowed.  Instead, use simply:</p>

<eg><![CDATA[<a href="#{id(@ref)/title}">]]></eg>

</div3>

</div2>

<div2 id="number">
<head>Numbering</head>

<e:element-syntax name="number">
  <e:in-category name="instruction"/>
  <e:attribute name="level">
    <e:constant value="single"/>
    <e:constant value="multiple"/>
    <e:constant value="any"/>
  </e:attribute>
  <e:attribute name="count">
    <e:data-type name="pattern"/>
  </e:attribute>
  <e:attribute name="from">
    <e:data-type name="pattern"/>
  </e:attribute>
  <e:attribute name="value">
    <e:data-type name="number-expression"/>
  </e:attribute>
  <e:attribute name="format">
    <e:attribute-value-template>
      <e:data-type name="string"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="lang">
    <e:attribute-value-template>
      <e:data-type name="nmtoken"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="letter-value">
    <e:attribute-value-template>
      <e:constant value="alphabetic"/>
      <e:constant value="traditional"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="grouping-separator">
    <e:attribute-value-template>
      <e:data-type name="char"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="grouping-size">
    <e:attribute-value-template>
      <e:data-type name="number"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>The <code>xsl:number</code> element is used to insert a formatted
number into the result tree.  The number to be inserted may be
specified by an expression. The <code>value</code> attribute contains
an <termref def="dt-expression">expression</termref>.  The expression
is evaluated and the resulting object is converted to a number as if
by a call to the <xfunction>number</xfunction> function.  The number is
rounded to an integer and then converted to a string using the
attributes specified in <specref ref="convert"/>; in this
context, the value of each of these attributes is
interpreted as an <termref def="dt-attribute-value-template">attribute
value template</termref>.  After conversion, the resulting string is
inserted in the result tree. For example, the following example
numbers a sorted list:</p>

<eg><![CDATA[<xsl:template match="items">
  <xsl:for-each select="item">
    <xsl:sort select="."/>
    <p>
      <xsl:number value="position()" format="1. "/>
      <xsl:value-of select="."/>
    </p>
  </xsl:for-each>
</xsl:template>]]></eg>

<p>If no <code>value</code> attribute is specified, then the
<code>xsl:number</code> element inserts a number based on the position
of the current node in the source tree. The following attributes
control how the current node is to be numbered:</p>

<ulist>

<item><p>The <code>level</code> attribute specifies what levels of the
source tree should be considered; it has the values
<code>single</code>, <code>multiple</code> or <code>any</code>. The
default is <code>single</code>.</p></item>

<item><p>The <code>count</code> attribute is a pattern that specifies
what nodes should be counted at those levels.  If <code>count</code>
attribute is not specified, then it defaults to the pattern that
matches any node with the same node type as the current node and, if
the current node has an expanded-name, with the same expanded-name as
the current node.</p></item>

<item><p>The <code>from</code> attribute is a pattern that specifies
where counting starts.</p></item>

</ulist>

<p>In addition, the attributes specified in <specref ref="convert"/>
are used for number to string conversion, as in the case when the
<code>value</code> attribute is specified.</p>

<p>The <code>xsl:number</code> element first constructs a list of
positive integers using the <code>level</code>, <code>count</code> and
<code>from</code> attributes:</p>

<ulist>

<item><p>When <code>level="single"</code>, it goes up to the first
node in the ancestor-or-self axis that matches
the <code>count</code> pattern, and constructs a list of length one
containing one plus the number of preceding siblings of that ancestor
that match the <code>count</code> pattern. If there is no such
ancestor, it constructs an empty list.  If the <code>from</code>
attribute is specified, then the only ancestors that are searched are
those that are descendants of the nearest ancestor that matches the
<code>from</code> pattern. Preceding siblings has the same meaning
here as with the <code>preceding-sibling</code> axis.</p></item>

<item><p>When <code>level="multiple"</code>, it constructs a list of all
ancestors of the current node in document order followed by the
element itself; it then selects from the list those nodes that match
the <code>count</code> pattern; it then maps each node in the list to
one plus the number of preceding siblings of that node that match the
<code>count</code> pattern.  If the <code>from</code> attribute is
specified, then the only ancestors that are searched are those that
are descendants of the nearest ancestor that matches the
<code>from</code> pattern. Preceding siblings has the same meaning
here as with the <code>preceding-sibling</code> axis.</p></item>

<item><p>When <code>level="any"</code>, it constructs a list of length
one containing the number of nodes that match the <code>count</code>
pattern and belong to the set containing the current node and all
nodes at any level of the document that are before the current node in
document order, excluding any namespace and attribute nodes (in other
words the union of the members of the <code>preceding</code> and
<code>ancestor-or-self</code> axes). If the <code>from</code>
attribute is specified, then only nodes after the first node before
the current node that match the <code>from</code> pattern are
considered.</p></item>

</ulist>

<p>The list of numbers is then converted into a string using the
attributes specified in <specref ref="convert"/>; in this
context, the value of each of these attributes is
interpreted as an <termref def="dt-attribute-value-template">attribute
value template</termref>.  After conversion, the resulting string is
inserted in the result tree.</p>

<p>The following would number the items in an ordered list:</p>

<eg><![CDATA[<xsl:template match="ol/item">
  <fo:block>
    <xsl:number/><xsl:text>. </xsl:text><xsl:apply-templates/>
  </fo:block>
<xsl:template>]]></eg>

<p>The following two rules would number <code>title</code> elements.
This is intended for a document that contains a sequence of chapters
followed by a sequence of appendices, where both chapters and
appendices contain sections, which in turn contain subsections.
Chapters are numbered 1, 2, 3; appendices are numbered A, B, C;
sections in chapters are numbered 1.1, 1.2, 1.3; sections in
appendices are numbered A.1, A.2, A.3.</p>

<eg><![CDATA[<xsl:template match="title">
  <fo:block>
     <xsl:number level="multiple"
                 count="chapter|section|subsection"
                 format="1.1 "/>
     <xsl:apply-templates/>
  </fo:block>
</xsl:template>

<xsl:template match="appendix//title" priority="1">
  <fo:block>
     <xsl:number level="multiple"
                 count="appendix|section|subsection"
                 format="A.1 "/>
     <xsl:apply-templates/>
  </fo:block>
</xsl:template>]]></eg>

<p>The following example numbers notes sequentially within a
chapter:</p>

<eg><![CDATA[<xsl:template match="note">
  <fo:block>
     <xsl:number level="any" from="chapter" format="(1) "/>
     <xsl:apply-templates/>
  </fo:block>
</xsl:template>]]></eg>

<p>The following example would number <code>H4</code> elements in HTML
with a three-part label:</p>

<eg><![CDATA[<xsl:template match="H4">
 <fo:block>
   <xsl:number level="any" from="H1" count="H2"/>
   <xsl:text>.</xsl:text>
   <xsl:number level="any" from="H2" count="H3"/>
   <xsl:text>.</xsl:text>
   <xsl:number level="any" from="H3" count="H4"/>
   <xsl:text> </xsl:text>
   <xsl:apply-templates/>
 </fo:block>
</xsl:template>]]></eg>

<div3 id="convert">
<head>Number to String Conversion Attributes</head>

<p>The following attributes are used to control conversion of a list
of numbers into a string. The numbers are integers greater than
0. The attributes are all optional.</p>

<p>The main attribute is <code>format</code>.  The default value for
the <code>format</code> attribute is <code>1</code>.  The
<code>format</code> attribute is split into a sequence of tokens where
each token is a maximal sequence of alphanumeric characters or a
maximal sequence of non-alphanumeric characters.  Alphanumeric means
any character that has a Unicode category of Nd, Nl, No, Lu, Ll, Lt,
Lm or Lo.  The alphanumeric tokens (format tokens) specify the format
to be used for each number in the list.  If the first token is a
non-alphanumeric token, then the constructed string will start with
that token; if the last token is non-alphanumeric token, then the
constructed string will end with that token.  Non-alphanumeric tokens
that occur between two format tokens are separator tokens that are
used to join numbers in the list.  The <var>n</var>th format token
will be used to format the <var>n</var>th number in the list.  If
there are more numbers than format tokens, then the last format token
will be used to format remaining numbers.  If there are no format
tokens, then a format token of <code>1</code> is used to format all
numbers.  The format token specifies the string to be used to
represent the number 1.  Each number after the first will be separated
from the preceding number by the separator token preceding the format
token used to format that number, or, if there are no separator
tokens, then by <code>.</code> (a period character).</p>

<p>Format tokens are a superset of the allowed values for the
<code>type</code> attribute for the <code>OL</code> element in HTML
4.0 and are interpreted as follows:</p>

<ulist>

<item><p>Any token where the last character has a decimal digit value
of 1 (as specified in the Unicode character property database),
and the Unicode value of preceding characters is one less than the
Unicode value of the last character generates a decimal
representation of the number where each number is at least as long as
the format token.  Thus, a format token <code>1</code> generates the
sequence <code>1 2 ... 10 11 12 ...</code>, and a format token
<code>01</code> generates the sequence <code>01 02 ... 09 10 11 12
... 99 100 101</code>.</p></item>

<item><p>A format token <code>A</code> generates the sequence <code>A
B C ... Z AA AB AC...</code>.</p></item>

<item><p>A format token <code>a</code> generates the sequence <code>a
b c ... z aa ab ac...</code>.</p></item>

<item><p>A format token <code>i</code> generates the sequence <code>i
ii iii iv v vi vii viii ix x ...</code>.</p></item>

<item><p>A format token <code>I</code> generates the sequence <code>I
II III IV V VI VII VIII IX X ...</code>.</p></item>

<item><p>Any other format token indicates a numbering sequence that
starts with that token.  If an implementation does not support a
numbering sequence that starts with that token, it must use a format
token of <code>1</code>.</p></item>

</ulist>

<p>When numbering with an alphabetic sequence, the <code>lang</code>
attribute specifies which language's alphabet is to be used; it has
the same range of values as <code>xml:lang</code> <bibref ref="XML"/>;
if no <code>lang</code> value is specified, the language should be
determined from the system environment.  Implementers should document
for which languages they support numbering.</p>

<note><p>Implementers should not make any assumptions about how
numbering works in particular languages and should properly research
the languages that they wish to support.  The numbering conventions of
many languages are very different from English.</p></note>

<p>The <code>letter-value</code> attribute disambiguates between
numbering sequences that use letters.  In many languages there are two
commonly used numbering sequences that use letters.  One numbering
sequence assigns numeric values to letters in alphabetic sequence, and
the other assigns numeric values to each letter in some other manner
traditional in that language.  In English, these would correspond to
the numbering sequences specified by the format tokens <code>a</code>
and <code>i</code>.  In some languages, the first member of each
sequence is the same, and so the format token alone would be
ambiguous.  A value of <code>alphabetic</code> specifies the
alphabetic sequence; a value of <code>traditional</code> specifies the
other sequence.  If the <code>letter-value</code> attribute is not
specified, then it is implementation-dependent how any ambiguity is
resolved.</p>

<note><p>It is possible for two conforming XSLT processors not to
convert a number to exactly the same string.  Some XSLT processors may not
support some languages.  Furthermore, there may be variations possible
in the way conversions are performed for any particular language that
are not specifiable by the attributes on <code>xsl:number</code>.
Future versions of XSLT may provide additional attributes to provide
control over these variations.  Implementations may also use
implementation-specific namespaced attributes on
<code>xsl:number</code> for this.</p></note>

<p>The <code>grouping-separator</code> attribute gives the separator
used as a grouping (e.g. thousands) separator in decimal numbering
sequences, and the optional <code>grouping-size</code> specifies the
size (normally 3) of the grouping.  For example,
<code>grouping-separator=","</code> and <code>grouping-size="3"</code>
would produce numbers of the form <code>1,000,000</code>.  If only one
of the <code>grouping-separator</code> and <code>grouping-size</code>
attributes is specified, then it is ignored.</p>

<p>Here are some examples of conversion specifications:</p>

<ulist>

<item><p><code>format="&amp;#x30A2;"</code> specifies Katakana
numbering</p></item>

<item><p><code>format="&amp;#x30A4;"</code> specifies Katakana
numbering in the <quote>iroha</quote> order</p></item>

<item><p><code>format="&amp;#x0E51;"</code> specifies numbering with
Thai digits</p></item>

<item><p><code>format="&amp;#x05D0;" letter-value="traditional"</code>
specifies <quote>traditional</quote> Hebrew numbering</p></item>

<item><p><code>format="&amp;#x10D0;" letter-value="traditional"</code>
specifies Georgian numbering</p></item>

<item><p><code>format="&amp;#x03B1;" letter-value="traditional"</code>
specifies <quote>classical</quote> Greek numbering</p></item>

<item><p><code>format="&amp;#x0430;" letter-value="traditional"</code>
specifies Old Slavic numbering</p></item>

</ulist>

</div3>
</div2>
</div1>

<div1 id="for-each">

<head>Repetition</head>

<e:element-syntax name="for-each">
  <e:in-category name="instruction"/>
  <e:attribute name="select" required="yes">
    <e:data-type name="node-set-expression"/>
  </e:attribute>
  <e:sequence>
    <e:element repeat="zero-or-more" name="sort"/>
    <e:model name="template"/>
  </e:sequence>
</e:element-syntax>

<p>When the result has a known regular structure, it is useful to be
able to specify directly the template for selected nodes.  The
<code>xsl:for-each</code> instruction contains a template, which is
instantiated for each node selected by the <termref
def="dt-expression">expression</termref> specified by the
<code>select</code> attribute. The <code>select</code> attribute is
required.  The expression must evaluate to a node-set.  The template
is instantiated with the selected node as the <termref
def="dt-current-node">current node</termref>, and with a list of all
of the selected nodes as the <termref
def="dt-current-node-list">current node list</termref>.  The nodes are
processed in document order, unless a sorting specification is present
(see <specref ref="sorting"/>).</p>

<p>For example, given an XML document with this structure</p>

<eg><![CDATA[<customers>
  <customer>
    <name>...</name>
    <order>...</order>
    <order>...</order>
  </customer>
  <customer>
    <name>...</name>
    <order>...</order>
    <order>...</order>
  </customer>
</customers>]]></eg>

<p>the following would create an HTML document containing a table with
a row for each <code>customer</code> element</p>

<eg><![CDATA[<xsl:template match="/">
  <html>
    <head>
      <title>Customers</title>
    </head>
    <body>
      <table>
	<tbody>
	  <xsl:for-each select="customers/customer">
	    <tr>
	      <th>
		<xsl:apply-templates select="name"/>
	      </th>
	      <xsl:for-each select="order">
		<td>
		  <xsl:apply-templates/>
		</td>
	      </xsl:for-each>
	    </tr>
	  </xsl:for-each>
	</tbody>
      </table>
    </body>
  </html>
</xsl:template>]]></eg>

</div1>

<div1>
<head>Conditional Processing</head>

<p>There are two instructions in XSLT that support conditional
processing in a template: <code>xsl:if</code> and
<code>xsl:choose</code>. The <code>xsl:if</code> instruction provides
simple if-then conditionality; the <code>xsl:choose</code> instruction
supports selection of one choice when there are several
possibilities.</p>

<div2>
<head>Conditional Processing with <code>xsl:if</code></head>

<e:element-syntax name="if">
  <e:in-category name="instruction"/>
  <e:attribute name="test" required="yes">
    <e:data-type name="boolean-expression"/>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<p>The <code>xsl:if</code> element has a <code>test</code> attribute,
which specifies an <termref def="dt-expression">expression</termref>.
The content is a template.  The expression is evaluated and the
resulting object is converted to a boolean as if by a call to the
<xfunction>boolean</xfunction> function.  If the result is true, then
the content template is instantiated; otherwise, nothing is created.
In the following example, the names in a group of names are formatted
as a comma separated list:</p>

<eg><![CDATA[<xsl:template match="namelist/name">
  <xsl:apply-templates/>
  <xsl:if test="not(position()=last())">, </xsl:if>
</xsl:template>]]></eg>

<p>The following colors every other table row yellow:</p>

<eg><![CDATA[<xsl:template match="item">
  <tr>
    <xsl:if test="position() mod 2 = 0">
       <xsl:attribute name="bgcolor">yellow</xsl:attribute>
    </xsl:if>
    <xsl:apply-templates/>
  </tr>
</xsl:template>]]></eg>

</div2>


<div2>
<head>Conditional Processing with <code>xsl:choose</code></head>

<e:element-syntax name="choose">
  <e:in-category name="instruction"/>
  <e:sequence>
    <e:element repeat="one-or-more" name="when"/>
    <e:element repeat="zero-or-one" name="otherwise"/>
  </e:sequence>
</e:element-syntax>

<e:element-syntax name="when">
  <e:attribute name="test" required="yes">
    <e:data-type name="boolean-expression"/>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<e:element-syntax name="otherwise">
  <e:model name="template"/>
</e:element-syntax>

<p>The <code>xsl:choose</code> element selects one among a number of
possible alternatives. It consists of a sequence of
<code>xsl:when</code> elements followed by an optional
<code>xsl:otherwise</code> element.  Each <code>xsl:when</code>
element has a single attribute, <code>test</code>, which specifies an
<termref def="dt-expression">expression</termref>. The content of the
<code>xsl:when</code> and <code>xsl:otherwise</code> elements is a
template.  When an <code>xsl:choose</code> element is processed, each
of the <code>xsl:when</code> elements is tested in turn, by evaluating
the expression and converting the resulting object to a boolean as if
by a call to the <xfunction>boolean</xfunction> function.  The content
of the first, and only the first, <code>xsl:when</code> element whose
test is true is instantiated.  If no <code>xsl:when</code> is true,
the content of the <code>xsl:otherwise</code> element is
instantiated. If no <code>xsl:when</code> element is true, and no
<code>xsl:otherwise</code> element is present, nothing is created.</p>

<p>The following example enumerates items in an ordered list using
arabic numerals, letters, or roman numerals depending on the depth to
which the ordered lists are nested.</p>

<eg><![CDATA[<xsl:template match="orderedlist/listitem">
  <fo:list-item indent-start='2pi'>
    <fo:list-item-label>
      <xsl:variable name="level"
                    select="count(ancestor::orderedlist) mod 3"/>
      <xsl:choose>
        <xsl:when test='$level=1'>
          <xsl:number format="i"/>
        </xsl:when>
        <xsl:when test='$level=2'>
          <xsl:number format="a"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:number format="1"/>
        </xsl:otherwise>
      </xsl:choose>
      <xsl:text>. </xsl:text>
    </fo:list-item-label>
    <fo:list-item-body>
      <xsl:apply-templates/>
    </fo:list-item-body>
  </fo:list-item>
</xsl:template>]]></eg>

</div2>
</div1>

<div1 id="sorting">
<head>Sorting</head>

<e:element-syntax name="sort">
  <e:attribute name="select">
    <e:data-type name="string-expression"/>
  </e:attribute>
  <e:attribute name="lang">
    <e:attribute-value-template>
      <e:data-type name="nmtoken"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="data-type">
    <e:attribute-value-template>
       <e:constant value="text"/>
       <e:constant value="number"/>
       <e:data-type name="qname-but-not-ncname"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="order">
    <e:attribute-value-template>
       <e:constant value="ascending"/>
       <e:constant value="descending"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:attribute name="case-order">
    <e:attribute-value-template>
       <e:constant value="upper-first"/>
       <e:constant value="lower-first"/>
    </e:attribute-value-template>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>Sorting is specified by adding <code>xsl:sort</code> elements as
children of an <code>xsl:apply-templates</code> or
<code>xsl:for-each</code> element.  The first <code>xsl:sort</code>
child specifies the primary sort key, the second <code>xsl:sort</code>
child specifies the secondary sort key and so on.  When an
<code>xsl:apply-templates</code> or <code>xsl:for-each</code> element
has one or more <code>xsl:sort</code> children, then instead of
processing the selected nodes in document order, it sorts the nodes
according to the specified sort keys and then processes them in sorted
order.  When used in <code>xsl:for-each</code>, <code>xsl:sort</code>
elements must occur first.  When a template is instantiated by
<code>xsl:apply-templates</code> and <code>xsl:for-each</code>, the
<termref def="dt-current-node-list">current node list</termref> list
consists of the complete list of nodes being processed in sorted
order.</p>

<p><code>xsl:sort</code> has a <code>select</code> attribute whose
value is an <termref def="dt-expression">expression</termref>. For
each node to be processed, the expression is evaluated with that node
as the current node and with the complete list of nodes being
processed in unsorted order as the current node list.
The resulting object is converted to a string as
if by a call to the <xfunction>string</xfunction> function; this string
is used as the sort key for that node. The default value of the
<code>select</code> attribute is <code>.</code>, which will cause the
string-value of the current node to be used as the sort key.</p>

<p>This string serves as a sort key for the node.  The following
optional attributes on <code>xsl:sort</code> control how the list of
sort keys are sorted; the values of all of these attributes are
interpreted as <termref def="dt-attribute-value-template">attribute
value templates</termref>.</p>

<ulist>

<item><p><code>order</code> specifies whether the strings should be
sorted in ascending or descending order; <code>ascending</code>
specifies ascending order; <code>descending</code> specifies
descending order; the default is <code>ascending</code></p></item>

<item><p><code>lang</code> specifies the language of the sort keys; it
has the same range of values as <code>xml:lang</code> <bibref
ref="XML"/>; if no <code>lang</code> value is specified, the language
should be determined from the system environment</p></item>

<item><p><code>data-type</code> specifies the data type of the
strings; the following values are allowed:</p>

<ulist>

<item><p><code>text</code> specifies that the sort keys should be
sorted lexicographically in the culturally correct manner for the
language specified by <code>lang</code></p></item>

<item><p><code>number</code> specifies that the sort keys should be
converted to numbers and then sorted according to the numeric value;
the sort key is converted to a number as if by a call to the
<xfunction>number</xfunction> function; the <code>lang</code>
attribute is ignored</p></item>

<item><p>a <xnt href="&XMLNames;#NT-QName">QName</xnt> with a prefix
is expanded into an <xtermref
href="&XPath;#dt-expanded-name">expanded-name</xtermref> as described
in <specref ref="qname"/>; the expanded-name identifies the data-type;
the behavior in this case is not specified by this document</p></item>

</ulist>

<p>The default value is <code>text</code>.</p>

<note><p>The XSL Working Group plans that future versions of XSLT will
leverage XML Schemas to define further values for this
attribute.</p></note>

</item>

<item><p><code>case-order</code> has the value
<code>upper-first</code> or <code>lower-first</code>; this applies
when <code>data-type="text"</code>, and specifies that upper-case
letters should sort before lower-case letters or vice-versa
respectively. For example, if <code>lang="en"</code>, then <code>A a B
b</code> are sorted with <code>case-order="upper-first"</code> and
<code>a A b B</code> are sorted with
<code>case-order="lower-first"</code>. The default value is language
dependent.</p></item>

</ulist>

<note><p>It is possible for two conforming XSLT processors not to sort
exactly the same.  Some XSLT processors may not support some
languages.  Furthermore, there may be variations possible in the
sorting of any particular language that are not specified by the
attributes on <code>xsl:sort</code>, for example, whether Hiragana or
Katakana is sorted first in Japanese.  Future versions of XSLT may
provide additional attributes to provide control over these
variations.  Implementations may also use implementation-specific
namespaced attributes on <code>xsl:sort</code> for this.</p></note>

<note><p>It is recommended that implementers consult <bibref
ref="UNICODE-TR10"/> for information on internationalized
sorting.</p></note>

<p>The sort must be stable: in the sorted list of nodes, any sub list
that has sort keys that all compare equal must be in document
order.</p>

<p>For example, suppose an employee database has the form</p>

<eg><![CDATA[<employees>
  <employee>
    <name>
      <given>James</given>
      <family>Clark</family>
    </name>
    ...
  </employee>
</employees>
]]></eg>
  
<p>Then a list of employees sorted by name could be generated
using:</p>

<eg><![CDATA[<xsl:template match="employees">
  <ul>
    <xsl:apply-templates select="employee">
      <xsl:sort select="name/family"/>
      <xsl:sort select="name/given"/>
    </xsl:apply-templates>
  </ul>
</xsl:template>

<xsl:template match="employee">
  <li>
    <xsl:value-of select="name/given"/>
    <xsl:text> </xsl:text>
    <xsl:value-of select="name/family"/>
  </li>
</xsl:template>]]></eg>

</div1>

<div1 id="variables">
<head>Variables and Parameters</head>

<e:element-syntax name="variable">
  <e:in-category name="top-level-element"/>
  <e:in-category name="instruction"/>
  <e:attribute name="name" required="yes">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:attribute name="select">
    <e:data-type name="expression"/>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<e:element-syntax name="param">
  <e:in-category name="top-level-element"/>
  <e:attribute name="name" required="yes">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:attribute name="select">
    <e:data-type name="expression"/>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<p>A variable is a name that may be bound to a value.  The value to
which a variable is bound (the <term>value</term> of the variable) can
be an object of any of the types that can be returned by expressions.
There are two elements that can be used to bind variables:
<code>xsl:variable</code> and <code>xsl:param</code>. The difference
is that the value specified on the <code>xsl:param</code> variable is
only a default value for the binding; when the template or stylesheet
within which the <code>xsl:param</code> element occurs is invoked,
parameters may be passed that are used in place of the default
values.</p>

<p>Both <code>xsl:variable</code> and <code>xsl:param</code> have a
required <code>name</code> attribute, which specifies the name of the
variable.  The value of the <code>name</code> attribute is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as described
in <specref ref="qname"/>.</p>

<p>For any use of these variable-binding elements, there is a region
of the stylesheet tree within which the binding is visible; within
this region, any binding of the variable that was visible on the
variable-binding element itself is hidden.  Thus, only the innermost
binding of a variable is visible.  The set of variable bindings in
scope for an expression consists of those bindings that are visible at
the point in the stylesheet where the expression occurs.</p>

<div2>
<head>Result Tree Fragments</head>

<p>Variables introduce an additional data-type into the expression
language.  <termdef id="dt-result-tree-fragment" term="Result Tree
Fragment">This additional data type is called <term>result tree
fragment</term>.  A variable may be bound to a result tree fragment
instead of one of the four basic XPath data-types (string, number,
boolean, node-set).  A result tree fragment represents a fragment of
the result tree. A result tree fragment is treated equivalently to a
node-set that contains just a single root node.</termdef> However, the
operations permitted on a result tree fragment are a subset of those
permitted on a node-set.  An operation is permitted on a result tree
fragment only if that operation would be permitted on a string (the
operation on the string may involve first converting the string to a
number or boolean). In particular, it is not permitted to use the
<code>/</code>, <code>//</code>, and <code>[]</code> operators on
result tree fragments.  When a permitted operation is performed on a
result tree fragment, it is performed exactly as it would be on the
equivalent node-set.</p>

<p>When a result tree fragment is copied into the result tree (see
<specref ref="copy-of"/>), then all the nodes that are children of the
root node in the equivalent node-set are added in sequence to the
result tree.</p>

<p>Expressions can only return values of type result tree fragment by
referencing variables of type result tree fragment or calling
extension functions that return a result tree fragment or getting a
system property whose value is a result tree fragment.</p>

</div2>

<div2 id="variable-values">
<head>Values of Variables and Parameters</head>

<p>A variable-binding element can specify the value of the variable in
three alternative ways.</p>

<ulist>

<item><p>If the variable-binding element has a <code>select</code>
attribute, then the value of the attribute must be an <termref
def="dt-expression">expression</termref> and the value of the variable
is the object that results from evaluating the expression.  In this
case, the content must be empty.</p></item>

<item>

<p>If the variable-binding element does not have a <code>select</code>
attribute and has non-empty content (i.e. the variable-binding element
has one or more child nodes), then the content of the
variable-binding element specifies the value. The content of the
variable-binding element is a template, which is instantiated to give
the value of the variable. The value is a result tree fragment
equivalent to a node-set containing just a single root node having as
children the sequence of nodes produced by instantiating the template.
The base URI of the nodes in the result tree fragment is the base URI
of the variable-binding element.</p>

<p>It is an error if a member of the sequence of nodes created by
instantiating the template is an attribute node or a namespace node,
since a root node cannot have an attribute node or a namespace node as
a child. An XSLT processor may signal the error; if it does not signal
the error, it must recover by not adding the attribute node or
namespace node.</p>

</item>

<item>

<p>If the variable-binding element has empty content and does not have
a <code>select</code> attribute, then the value of the variable is an
empty string. Thus</p>

<eg><![CDATA[<xsl:variable name="x"/>]]></eg>

<p>is equivalent to</p>

<eg><![CDATA[<xsl:variable name="x" select="''"/>]]></eg>

</item>

</ulist>

<note><p>When a variable is used to select nodes by position, be careful
not to do:</p>

<eg><![CDATA[<xsl:variable name="n">2</xsl:variable>
...
<xsl:value-of select="item[$n]"/>]]></eg>

<p>This will output the value of the first item element, because the
variable <code>n</code> will be bound to a result tree fragment, not a
number. Instead, do either</p>

<eg><![CDATA[<xsl:variable name="n" select="2"/>
...
<xsl:value-of select="item[$n]"/>]]></eg>

<p>or</p>

<eg><![CDATA[<xsl:variable name="n">2</xsl:variable>
...
<xsl:value-of select="item[position()=$n]"/>]]></eg>
</note>

<note><p>One convenient way to specify the empty node-set as the default
value of a parameter is:</p>

<eg><![CDATA[<xsl:param name="x" select="/.."/>]]></eg>
</note>

</div2>

<div2 id="copy-of">
<head>Using Values of Variables and Parameters with
<code>xsl:copy-of</code></head>

<e:element-syntax name="copy-of">
  <e:in-category name="instruction"/>
  <e:attribute name="select" required="yes">
    <e:data-type name="expression"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>The <code>xsl:copy-of</code> element can be used to insert a result
tree fragment into the result tree, without first converting it to a
string as <code>xsl:value-of</code> does (see <specref
ref="value-of"/>).  The required <code>select</code> attribute
contains an <termref def="dt-expression">expression</termref>.  When
the result of evaluating the expression is a result tree fragment, the
complete fragment is copied into the result tree.  When the result is
a node-set, all the nodes in the set are copied in document order into
the result tree; copying an element node copies the attribute nodes,
namespace nodes and children of the element node as well as the
element node itself; a root node is copied by copying its children.
When the result is neither a node-set nor a result tree fragment, the
result is converted to a string and then inserted into the result
tree, as with <code>xsl:value-of</code>.</p>

</div2>

<div2 id="top-level-variables">
<head>Top-level Variables and Parameters</head>

<p>Both <code>xsl:variable</code> and <code>xsl:param</code> are
allowed as <termref def="dt-top-level">top-level</termref> elements.
A top-level variable-binding element declares a global variable that
is visible everywhere.  A top-level <code>xsl:param</code> element
declares a parameter to the stylesheet; XSLT does not define the
mechanism by which parameters are passed to the stylesheet.  It is an
error if a stylesheet contains more than one binding of a top-level
variable with the same name and same <termref
def="dt-import-precedence">import precedence</termref>. At the
top-level, the expression or template specifying the variable value is
evaluated with the same context as that used to process the root node
of the source document: the current node is the root node of the
source document and the current node list is a list containing just
the root node of the source document.  If the template or expression
specifying the value of a global variable <var>x</var> references a
global variable <var>y</var>, then the value for <var>y</var> must
be computed before the value of <var>x</var>.  It is an error if it
is impossible to do this for all global variable definitions; in other
words, it is an error if the definitions are circular.</p>

<p>This example declares a global variable <code>para-font-size</code>,
which it references in an attribute value template.</p>

<eg><![CDATA[<xsl:variable name="para-font-size">12pt</xsl:variable>

<xsl:template match="para">
 <fo:block font-size="{$para-font-size}">
   <xsl:apply-templates/>
 </fo:block>
</xsl:template>
]]></eg>

</div2>

<div2 id="local-variables">
<head>Variables and Parameters within Templates</head>

<p>As well as being allowed at the top-level, both
<code>xsl:variable</code> and <code>xsl:param</code> are also
allowed in templates.  <code>xsl:variable</code> is allowed anywhere
within a template that an instruction is allowed.  In this case, the
binding is visible for all following siblings and their descendants.
Note that the binding is not visible for the <code>xsl:variable</code>
element itself.  <code>xsl:param</code> is allowed as a child
at the beginning of an <code>xsl:template</code> element.  In this
context, the binding is visible for all following siblings and their
descendants.  Note that the binding is not visible for the
<code>xsl:param</code> element itself.</p>

<p><termdef id="dt-shadows" term="Shadows">A binding
<term>shadows</term> another binding if the binding occurs at a point
where the other binding is visible, and the bindings have the same
name.</termdef> It is an error if a binding established by an
<code>xsl:variable</code> or <code>xsl:param</code> element within a
template <termref def="dt-shadows">shadows</termref> another binding
established by an <code>xsl:variable</code> or <code>xsl:param</code>
element also within the template.  It is not an error if a binding
established by an <code>xsl:variable</code> or <code>xsl:param</code>
element in a template <termref def="dt-shadows">shadows</termref>
another binding established by an <code>xsl:variable</code> or
<code>xsl:param</code> <termref def="dt-top-level">top-level</termref>
element.  Thus, the following is an error:</p>

<eg role="error"><![CDATA[<xsl:template name="foo">
<xsl:param name="x" select="1"/>
<xsl:variable name="x" select="2"/>
</xsl:template>]]></eg>

<p>However, the following is allowed:</p>

<eg><![CDATA[<xsl:param name="x" select="1"/>
<xsl:template name="foo">
<xsl:variable name="x" select="2"/>
</xsl:template>]]></eg>

<note><p>The nearest equivalent in Java to an <code>xsl:variable</code>
element in a template is a final local variable declaration with an
initializer.  For example,</p>

<eg><![CDATA[<xsl:variable name="x" select="'value'"/>]]></eg>

<p>has similar semantics to</p>

<eg>final Object x = "value";</eg>

<p>XSLT does not provide an equivalent to the Java assignment operator</p>

<eg>x = "value";</eg>

<p>because this would make it harder to create an implementation that
processes a document other than in a batch-like way, starting at the
beginning and continuing through to the end.</p></note>

</div2>

<div2>
<head>Passing Parameters to Templates</head>

<e:element-syntax name="with-param">
  <e:attribute name="name" required="yes">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:attribute name="select">
    <e:data-type name="expression"/>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<p>Parameters are passed to templates using the
<code>xsl:with-param</code> element.  The required <code>name</code>
attribute specifies the name of the parameter (the variable the value
of whose binding is to be replaced).  The value of the
<code>name</code> attribute is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as described
in <specref ref="qname"/>.  <code>xsl:with-param</code> is allowed
within both <code>xsl:call-template</code> and
<code>xsl:apply-templates</code>.  The value of the parameter is
specified in the same way as for <code>xsl:variable</code> and
<code>xsl:param</code>.  The current node and current node list used
for computing the value specified by <code>xsl:with-param</code>
element is the same as that used for the
<code>xsl:apply-templates</code> or <code>xsl:call-template</code>
element within which it occurs.  It is not an error to pass a
parameter <var>x</var> to a template that does not have an
<code>xsl:param</code> element for <var>x</var>; the parameter is
simply ignored.</p>

<p>This example defines a named template for a
<code>numbered-block</code> with an argument to control the format of
the number.</p>

<eg><![CDATA[<xsl:template name="numbered-block">
  <xsl:param name="format">1. </xsl:param>
  <fo:block>
    <xsl:number format="{$format}"/>
    <xsl:apply-templates/>
  </fo:block>
</xsl:template>

<xsl:template match="ol//ol/li">
  <xsl:call-template name="numbered-block">
    <xsl:with-param name="format">a. </xsl:with-param>
  </xsl:call-template>
</xsl:template>]]></eg>

</div2>

</div1>

<div1 id="add-func">
<head>Additional Functions</head>

<p>This section describes XSLT-specific additions to the core XPath
function library.  Some of these additional functions also make use of
information specified by <termref def="dt-top-level">top-level</termref>
elements in the stylesheet; this section also describes these
elements.</p>

<div2 id="document">

<head>Multiple Source Documents</head>

<proto name="document" return-type="node-set"><arg type="object"/>
<arg type="node-set" occur="opt"/></proto>

<p>The <function>document</function> function allows
access to XML documents other than the main source document.</p>

<p>When the <function>document</function> function has exactly one
argument and the argument is a node-set, then the result is the union,
for each node in the argument node-set, of the result of calling the
<function>document</function> function with the first argument being
the <xtermref href="&XPath;#dt-string-value">string-value</xtermref>
of the node, and the second argument being a node-set with the node as
its only member. When the <function>document</function> function has
two arguments and the first argument is a node-set, then the result is
the union, for each node in the argument node-set, of the result of
calling the <function>document</function> function with the first
argument being the <xtermref
href="&XPath;#dt-string-value">string-value</xtermref> of the node,
and with the second argument being the second argument passed to the
<function>document</function> function.</p>

<p>When the first argument to the <function>document</function>
function is not a node-set, the first argument is converted to a
string as if by a call to the <xfunction>string</xfunction> function.
This string is treated as a URI reference; the resource identified by
the URI is retrieved. The data resulting from the retrieval action is
parsed as an XML document and a tree is constructed in accordance with
the data model (see <specref ref="data-model"/>).  If there is an
error retrieving the resource, then the XSLT processor may signal an
error; if it does not signal an error, it must recover by returning an
empty node-set.  One possible kind of retrieval error is that the XSLT
processor does not support the URI scheme used by the URI.  An XSLT
processor is not required to support any particular URI schemes.  The
documentation for an XSLT processor should specify which URI schemes
the XSLT processor supports.</p>

<p>If the URI reference does not contain a fragment identifier, then a
node-set containing just the root node of the document is returned.
If the URI reference does contain a fragment identifier, the function
returns a node-set containing the nodes in the tree identified by the
fragment identifier of the URI reference. The semantics of the
fragment identifier is dependent on the media type of the result of
retrieving the URI.  If there is an error in processing the fragment
identifier, the XSLT processor may signal the error; if it does not
signal the error, it must recover by returning an empty node-set.
Possible errors include:</p>

<ulist>

<item><p>The fragment identifier identifies something that cannot be
represented by an XSLT node-set (such as a range of characters within
a text node).</p></item>

<item><p>The XSLT processor does not support fragment identifiers for
the media-type of the retrieval result.  An XSLT processor is not
required to support any particular media types.  The documentation for
an XSLT processor should specify for which media types the XSLT
processor supports fragment identifiers.</p></item>

</ulist>

<p>The data resulting from the retrieval action is parsed as an XML
document regardless of the media type of the retrieval result; if the
top-level media type is <code>text</code>, then it is parsed in the
same way as if the media type were <code>text/xml</code>; otherwise,
it is parsed in the same way as if the media type were
<code>application/xml</code>.</p>

<note><p>Since there is no top-level <code>xml</code> media type, data
with a media type other than <code>text/xml</code> or
<code>application/xml</code> may in fact be XML.</p></note>

<p>The URI reference may be relative. The base URI (see <specref
ref="base-uri"/>) of the node in the second argument node-set that is
first in document order is used as the base URI for resolving the
relative URI into an absolute URI.  If the second argument is omitted,
then it defaults to the node in the stylesheet that contains the
expression that includes the call to the <function>document</function>
function.  Note that a zero-length URI reference is a reference to the
document relative to which the URI reference is being resolved; thus
<code>document("")</code> refers to the root node of the stylesheet;
the tree representation of the stylesheet is exactly the same as if
the XML document containing the stylesheet was the initial source
document.</p>

<p>Two documents are treated as the same document if they are
identified by the same URI. The URI used for the comparison is the
absolute URI into which any relative URI was resolved and does not
include any fragment identifier.  One root node is treated as the same
node as another root node if the two nodes are from the same document.
Thus, the following expression will always be true:</p>

<eg>generate-id(document("foo.xml"))=generate-id(document("foo.xml"))</eg>

<p>The <function>document</function> function gives rise to the
possibility that a node-set may contain nodes from more than one
document.  With such a node-set, the relative document order of two
nodes in the same document is the normal <xtermref
href="&XPath;#dt-document-order">document order</xtermref> defined by
XPath <bibref ref="XPATH"/>.  The relative document order of two nodes
in different documents is determined by an implementation-dependent
ordering of the documents containing the two nodes.  There are no
constraints on how the implementation orders documents other than that
it must do so consistently: an implementation must always use the same
order for the same set of documents.</p>

</div2>

<div2 id="key">
<head>Keys</head>

<p>Keys provide a way to work with documents that contain an implicit
cross-reference structure.  The <code>ID</code>, <code>IDREF</code>
and <code>IDREFS</code> attribute types in XML provide a mechanism to
allow XML documents to make their cross-reference explicit.  XSLT
supports this through the XPath <xfunction>id</xfunction> function.
However, this mechanism has a number of limitations:</p>

<ulist>

<item><p>ID attributes must be declared as such in the DTD.  If an ID
attribute is declared as an ID attribute only in the external DTD
subset, then it will be recognized as an ID attribute only if the XML
processor reads the external DTD subset.  However, XML does not require
XML processors to read the external DTD, and they may well choose not
to do so, especially if the document is declared
<code>standalone="yes"</code>.</p></item>

<item><p>A document can contain only a single set of unique IDs.
There cannot be separate independent sets of unique IDs.</p></item>

<item><p>The ID of an element can only be specified in an attribute;
it cannot be specified by the content of the element, or by a child
element.</p></item>

<item><p>An ID is constrained to be an XML name.  For example, it
cannot contain spaces.</p></item>

<item><p>An element can have at most one ID.</p></item>

<item><p>At most one element can have a particular ID.</p></item>

</ulist>

<p>Because of these limitations XML documents sometimes contain a
cross-reference structure that is not explicitly declared by
ID/IDREF/IDREFS attributes.</p>

<p>A key is a triple containing:</p>

<olist>

<item><p>the node which has the key</p></item>

<item><p>the name of the key (an <xtermref
href="&XPath;#dt-expanded-name">expanded-name</xtermref>)</p></item>

<item><p>the value of the key (a string)</p></item>

</olist>

<p>A stylesheet declares a set of keys for each document using the
<code>xsl:key</code> element.  When this set of keys contains a member
with node <var>x</var>, name <var>y</var> and value
<var>z</var>, we say that node <var>x</var> has a key with name
<var>y</var> and value <var>z</var>.</p>

<p>Thus, a key is a kind of generalized ID, which is not subject to the
same limitations as an XML ID:</p>

<ulist>

<item><p>Keys are declared in the stylesheet using
<code>xsl:key</code> elements.</p></item>

<item><p>A key has a name as well as a value; each key name may be
thought of as distinguishing a separate, independent space of
identifiers.</p></item>

<item><p>The value of a named key for an element may be specified in
any convenient place; for example, in an attribute, in a child element
or in content.  An XPath expression is used to specify where to find
the value for a particular named key.</p></item>

<item><p>The value of a key can be an arbitrary string; it is not
constrained to be a name.</p></item>

<item><p>There can be multiple keys in a document with the same node,
same key name, but different key values.</p></item>

<item><p>There can be multiple keys in a document with the same key
name, same key value, but different nodes.</p></item>

</ulist>

<e:element-syntax name="key">
  <e:in-category name="top-level-element"/>
  <e:attribute name="name" required="yes">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:attribute name="match" required="yes">
    <e:data-type name="pattern"/>
  </e:attribute>
  <e:attribute name="use" required="yes">
    <e:data-type name="expression"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>The <code>xsl:key</code> element is used to declare keys.  The
<code>name</code> attribute specifies the name of the key.  The value
of the <code>name</code> attribute is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as described
in <specref ref="qname"/>. The <code>match</code> attribute is a <nt
def="NT-Pattern">Pattern</nt>; an <code>xsl:key</code> element gives
information about the keys of any node that matches the pattern
specified in the match attribute.  The <code>use</code> attribute is
an <termref def="dt-expression">expression</termref> specifying the
values of the key; the expression is evaluated once for each node that
matches the pattern.  If the result is a node-set, then for each node
in the node-set, the node that matches the pattern has a key of the
specified name whose value is the string-value of the node in the
node-set; otherwise, the result is converted to a string, and the node
that matches the pattern has a key of the specified name with value
equal to that string.  Thus, a node <var>x</var> has a key with name
<var>y</var> and value <var>z</var> if and only if there is an
<code>xsl:key</code> element such that:</p>

<ulist>

<item><p><var>x</var> matches the pattern specified in the
<code>match</code> attribute of the <code>xsl:key</code> element;</p></item>

<item><p>the value of the <code>name</code> attribute of the
<code>xsl:key</code> element is equal to <var>y</var>;
and</p></item>

<item><p>when the expression specified in the <code>use</code>
attribute of the <code>xsl:key</code> element is evaluated with
<var>x</var> as the current node and with a node list containing
just <var>x</var> as the current node list resulting in an object
<var>u</var>, then either <var>z</var> is equal to the result of
converting <var>u</var> to a string as if by a call to the
<xfunction>string</xfunction> function, or <var>u</var> is a
node-set and <var>z</var> is equal to the string-value of one or
more of the nodes in <var>u</var>.</p></item>

</ulist>

<p>Note also that there may be more than one <code>xsl:key</code>
element that matches a given node; all of the matching
<code>xsl:key</code> elements are used, even if they do not have the
same <termref def="dt-import-precedence">import
precedence</termref>.</p>

<p>It is an error for the value of either the <code>use</code>
attribute or the <code>match</code> attribute to contain a <xnt
href="&XPath;#NT-VariableReference">VariableReference</xnt>.</p>

<proto name="key" return-type="node-set"><arg type="string"/><arg type="object"/></proto>

<p>The <function>key</function> function does for keys what the
<xfunction>id</xfunction> function does for IDs.  The first argument
specifies the name of the key. The value of the argument must be a
<xnt href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as
described in <specref ref="qname"/>. When the second argument to the
<function>key</function> function is of type node-set, then the result
is the union of the result of applying the <function>key</function>
function to the string <xtermref
href="&XPath;#dt-value">value</xtermref> of each of the nodes in the
argument node-set.  When the second argument to
<function>key</function> is of any other type, the argument is
converted to a string as if by a call to the
<xfunction>string</xfunction> function; it returns a node-set
containing the nodes in the same document as the context node that
have a value for the named key equal to this string.</p>

<p>For example, given a declaration</p>

<eg><![CDATA[<xsl:key name="idkey" match="div" use="@id"/>]]></eg>

<p>an expression <code>key("idkey",@ref)</code> will return the same
node-set as <code>id(@ref)</code>, assuming that the only ID attribute
declared in the XML source document is:</p>

<eg><![CDATA[<!ATTLIST div id ID #IMPLIED>]]></eg>

<p>and that the <code>ref</code> attribute of the current node
contains no whitespace.</p>

<p>Suppose a document describing a function library uses a
<code>prototype</code> element to define functions</p>

<eg><![CDATA[<prototype name="key" return-type="node-set">
<arg type="string"/>
<arg type="object"/>
</prototype>]]></eg>

<p>and a <code>function</code> element to refer to function names</p>

<eg><![CDATA[<function>key</function>]]></eg>

<p>Then the stylesheet could generate hyperlinks between the
references and definitions as follows:</p>

<eg><![CDATA[<xsl:key name="func" match="prototype" use="@name"/>

<xsl:template match="function">
<b>
  <a href="#{generate-id(key('func',.))}">
    <xsl:apply-templates/>
  </a>
</b>
</xsl:template>

<xsl:template match="prototype">
<p><a name="{generate-id()}">
<b>Function: </b>
...
</a></p>
</xsl:template>]]></eg>

<p>The <function>key</function> can be used to retrieve a key from a
document other than the document containing the context node.  For
example, suppose a document contains bibliographic references in the
form <code><![CDATA[<bibref>XSLT</bibref>]]></code>, and there is a
separate XML document <code>bib.xml</code> containing a bibliographic
database with entries in the form:</p>

<eg><![CDATA[<entry name="XSLT">...</entry>]]></eg>

<p>Then the stylesheet could use the following to transform the
<code>bibref</code> elements:</p>

<eg><![CDATA[<xsl:key name="bib" match="entry" use="@name"/>

<xsl:template match="bibref">
  <xsl:variable name="name" select="."/>
  <xsl:for-each select="document('bib.xml')">
    <xsl:apply-templates select="key('bib',$name)"/>
  </xsl:for-each>
</xsl:template>]]></eg>

</div2>

<div2 id="format-number">
<head>Number Formatting</head>

<proto name="format-number" return-type="string"><arg type="number"/><arg type="string"/><arg occur="opt" type="string"/></proto>

<p>The <function>format-number</function> function converts its first
argument to a string using the format pattern string specified by the
second argument and the decimal-format named by the third argument, or
the default decimal-format, if there is no third argument.  The format
pattern string is in the syntax specified by the JDK 1.1 <loc href=
"http://java.sun.com/products/jdk/1.1/docs/api/java.text.DecimalFormat.html"
>DecimalFormat</loc> class. The format pattern string is in a
localized notation: the decimal-format determines what characters have
a special meaning in the pattern (with the exception of the quote
character, which is not localized).  The format pattern must not
contain the currency sign (#x00A4); support for this feature was added
after the initial release of JDK 1.1.  The decimal-format name must be
a <xnt href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as
described in <specref ref="qname"/>.  It is an error if the stylesheet
does not contain a declaration of the decimal-format with the specified
<xtermref href="&XPath;#dt-expanded-name">expanded-name</xtermref>.</p>

<note><p>Implementations are not required to use the JDK 1.1
implementation, nor are implementations required to be implemented in
Java.</p></note>

<note><p>Stylesheets can use other facilities in XPath to control
rounding.</p></note>

<e:element-syntax name="decimal-format">
  <e:in-category name="top-level-element"/>
  
  <e:attribute name="name">
    <e:data-type name="qname"/>
  </e:attribute>
  <e:attribute name="decimal-separator">
    <e:data-type name="char"/>
  </e:attribute>
  <e:attribute name="grouping-separator">
    <e:data-type name="char"/>
  </e:attribute>
  <e:attribute name="infinity">
    <e:data-type name="string"/>
  </e:attribute>
  <e:attribute name="minus-sign">
    <e:data-type name="char"/>
  </e:attribute>
  <e:attribute name="NaN">
    <e:data-type name="string"/>
  </e:attribute>
  <e:attribute name="percent">
    <e:data-type name="char"/>
  </e:attribute>
  <e:attribute name="per-mille">
    <e:data-type name="char"/>
  </e:attribute>
  <e:attribute name="zero-digit">
    <e:data-type name="char"/>
  </e:attribute>
  <e:attribute name="digit">
    <e:data-type name="char"/>
  </e:attribute>
  <e:attribute name="pattern-separator">
    <e:data-type name="char"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>The <code>xsl:decimal-format</code> element declares a
decimal-format, which controls the interpretation of a format pattern
used by the <function>format-number</function> function.  If there is
a <code>name</code> attribute, then the element declares a named
decimal-format; otherwise, it declares the default decimal-format.
The value of the <code>name</code> attribute is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>, which is expanded as described
in <specref ref="qname"/>.  It is an error to declare either the
default decimal-format or a decimal-format with a given name more than
once (even with different <termref def="dt-import-precedence">import
precedence</termref>), unless it is declared every time with the same
value for all attributes (taking into account any default values).</p>

<p>The other attributes on <code>xsl:decimal-format</code> correspond
to the methods on the JDK 1.1 <loc href=
"http://java.sun.com/products/jdk/1.1/docs/api/java.text.DecimalFormatSymbols.html"
>DecimalFormatSymbols</loc> class.  For each
<code>get</code>/<code>set</code> method pair there is an attribute
defined for the <code>xsl:decimal-format</code> element.</p>

<p>The following attributes both control the interpretation of
characters in the format pattern and specify characters that may
appear in the result of formatting the number:</p>

<ulist>

<item><p><code>decimal-separator</code> specifies the character used
for the decimal sign; the default value is the period character
(<code>.</code>)</p></item>

<item><p><code>grouping-separator</code> specifies the character used
as a grouping (e.g. thousands) separator; the default value is the
comma character (<code>,</code>)</p></item>

<item><p><code>percent</code> specifies the character used as a
percent sign; the default value is the percent character
(<code>%</code>)</p></item>

<item><p><code>per-mille</code> specifies the character used as a per
mille sign; the default value is the Unicode per-mille character
(#x2030)</p></item>

<item><p><code>zero-digit</code> specifies the character used as the
digit zero; the default value is the digit zero
(<code>0</code>)</p></item>

</ulist>

<p>The following attributes control the interpretation of characters
in the format pattern:</p>

<ulist>

<item><p><code>digit</code> specifies the character used for a digit
in the format pattern; the default value is the number sign character
(<code>#</code>)</p></item>

<item><p><code>pattern-separator</code> specifies the character used
to separate positive and negative sub patterns in a pattern; the
default value is the semi-colon character (<code>;</code>)</p></item>

</ulist>

<p>The following attributes specify characters or strings that may
appear in the result of formatting the number:</p>

<ulist>

<item><p><code>infinity</code> specifies the string used to represent
infinity; the default value is the string
<code>Infinity</code></p></item>

<item><p><code>NaN</code> specifies the string used to represent the
NaN value; the default value is the string <code>NaN</code></p></item>

<item><p><code>minus-sign</code> specifies the character used as the
default minus sign; the default value is the hyphen-minus character
(<code>-</code>, #x2D)</p></item>

</ulist>

</div2>

<div2 id="misc-func">
<head>Miscellaneous Additional Functions</head>

<proto name="current" return-type="node-set"></proto>

<p>The <function>current</function> function returns a node-set that
has the <termref def="dt-current-node">current node</termref> as its
only member.  For an outermost expression (an expression not occurring
within another expression), the current node is always the same as the
context node.  Thus,</p>

<eg><![CDATA[<xsl:value-of select="current()"/>]]></eg>

<p>means the same as</p>

<eg><![CDATA[<xsl:value-of select="."/>]]></eg>

<p>However, within square brackets the current node is usually
different from the context node. For example,</p>

<eg><![CDATA[<xsl:apply-templates select="//glossary/item[@name=current()/@ref]"/>]]></eg>

<p>will process all <code>item</code> elements that have a
<code>glossary</code> parent element and that have a <code>name</code>
attribute with value equal to the value of the current node's
<code>ref</code> attribute. This is different from</p>

<eg><![CDATA[<xsl:apply-templates select="//glossary/item[@name=./@ref]"/>]]></eg>

<p>which means the same as</p>

<eg><![CDATA[<xsl:apply-templates select="//glossary/item[@name=@ref]"/>]]></eg>

<p>and so would process all <code>item</code> elements that have a
<code>glossary</code> parent element and that have a <code>name</code>
attribute and a <code>ref</code> attribute with the same value.</p>

<p>It is an error to use the <function>current</function> function in
a <termref def="dt-pattern">pattern</termref>.</p>

<proto name="unparsed-entity-uri" return-type="string"><arg type="string"/></proto>

<p>The <function>unparsed-entity-uri</function> returns the URI of the
unparsed entity with the specified name in the same document as the
context node (see <specref ref="unparsed-entities"/>).  It returns the
empty string if there is no such entity.</p>

<proto name="generate-id" return-type="string"><arg occur="opt" type="node-set"/></proto>

<p>The <function>generate-id</function> function returns a string that
uniquely identifies the node in the argument node-set that is first in
document order.  The unique identifier must consist of ASCII
alphanumeric characters and must start with an alphabetic character.
Thus, the string is syntactically an XML name.  An implementation is
free to generate an identifier in any convenient way provided that it
always generates the same identifier for the same node and that
different identifiers are always generated from different nodes. An
implementation is under no obligation to generate the same identifiers
each time a document is transformed.  There is no guarantee that a
generated unique identifier will be distinct from any unique IDs
specified in the source document.  If the argument node-set is empty,
the empty string is returned. If the argument is omitted, it defaults
to the context node.</p>

<proto name="system-property" return-type="object"><arg type="string"/></proto>

<p>The argument must evaluate to a string that is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>.  The <xnt
href="&XMLNames;#NT-QName">QName</xnt> is expanded into a name using
the namespace declarations in scope for the expression. The
<function>system-property</function> function returns an object
representing the value of the system property identified by the name.
If there is no such system property, the empty string should be
returned.</p>

<p>Implementations must provide the following system properties, which
are all in the XSLT namespace:</p>

<slist>

<sitem><code>xsl:version</code>, a number giving the version of XSLT
implemented by the processor; for XSLT processors implementing the
version of XSLT specified by this document, this is the number
1.0</sitem>

<sitem><code>xsl:vendor</code>, a string identifying the vendor of the
XSLT processor</sitem>

<sitem><code>xsl:vendor-url</code>, a string containing a URL
identifying the vendor of the XSLT processor; typically this is the
host page (home page) of the vendor's Web site.</sitem>

</slist>

</div2>

</div1>

<div1 id="message">
<head>Messages</head>

<e:element-syntax name="message">
  <e:in-category name="instruction"/>
  <e:attribute name="terminate">
    <e:constant value="yes"/>
    <e:constant value="no"/>
  </e:attribute>
  <e:model name="template"/>
</e:element-syntax>

<p>The <code>xsl:message</code> instruction sends a message in a way
that is dependent on the XSLT processor.  The content of the
<code>xsl:message</code> instruction is a template.  The
<code>xsl:message</code> is instantiated by instantiating the content
to create an XML fragment.  This XML fragment is the content of the
message.</p>

<note><p>An XSLT processor might implement <code>xsl:message</code> by
popping up an alert box or by writing to a log file.</p></note>

<p>If the <code>terminate</code> attribute has the value
<code>yes</code>, then the XSLT processor should terminate processing
after sending the message.  The default value is <code>no</code>.</p>

<p>One convenient way to do localization is to put the localized
information (message text, etc.) in an XML document, which becomes an
additional input file to the stylesheet.  For example, suppose
messages for a language <code><var>L</var></code> are stored in an XML
file <code>resources/<var>L</var>.xml</code> in the form:</p>

<eg><![CDATA[<messages>
  <message name="problem">A problem was detected.</message>
  <message name="error">An error was detected.</message>
</messages>
]]></eg>

<p>Then a stylesheet could use the following approach to localize
messages:</p>

<eg><![CDATA[<xsl:param name="lang" select="en"/>
<xsl:variable name="messages"
  select="document(concat('resources/', $lang, '.xml'))/messages"/>

<xsl:template name="localized-message">
  <xsl:param name="name"/>
  <xsl:message>
    <xsl:value-of select="$messages/message[@name=$name]"/>
  </xsl:message>
</xsl:template>

<xsl:template name="problem">
  <xsl:call-template name="localized-message"/>
    <xsl:with-param name="name">problem</xsl:with-param>
  </xsl:call-template>
</xsl:template>]]></eg>

</div1>

<div1 id="extension">
<head>Extensions</head>

<p>XSLT allows two kinds of extension, extension elements and
extension functions.</p>

<p>This version of XSLT does not provide a mechanism for defining
implementations of extensions.  Therefore, an XSLT stylesheet that must
be portable between XSLT implementations cannot rely on particular
extensions being available.  XSLT provides mechanisms that allow an
XSLT stylesheet to determine whether the XSLT processor by which it is
being processed has implementations of particular extensions
available, and to specify what should happen if those extensions are
not available.  If an XSLT stylesheet is careful to make use of these
mechanisms, it is possible for it to take advantage of extensions and
still work with any XSLT implementation.</p>

<div2 id="extension-element">
<head>Extension Elements</head>

<p><termdef id="dt-extension-namespace" term="Extension Namespace">The
element extension mechanism allows namespaces to be designated as
<term>extension namespace</term>s. When a namespace is designated as
an extension namespace and an element with a name from that namespace
occurs in a template, then the element is treated as an instruction
rather than as a literal result element.</termdef> The namespace
determines the semantics of the instruction.</p>

<note><p>Since an element that is a child of an
<code>xsl:stylesheet</code> element is not occurring <emph>in a
template</emph>, non-XSLT <termref
def="dt-top-level">top-level</termref> elements are not extension
elements as defined here, and nothing in this section applies to
them.</p></note>

<p>A namespace is designated as an extension namespace by using an
<code>extension-element-prefixes</code> attribute on an
<code>xsl:stylesheet</code> element or an
<code>xsl:extension-element-prefixes</code> attribute on a literal
result element or extension element.
The value of both these attributes is a
whitespace-separated list of namespace prefixes. The namespace bound
to each of the prefixes is designated as an extension namespace.  It
is an error if there is no namespace bound to the prefix on the
element bearing the <code>extension-element-prefixes</code> or
<code>xsl:extension-element-prefixes</code> attribute.  The default
namespace (as declared by <code>xmlns</code>) may be designated as an
extension namespace by including <code>#default</code> in the list of
namespace prefixes.  The designation of a namespace as an extension
namespace is effective within the subtree of the stylesheet rooted at
the element bearing the <code>extension-element-prefixes</code> or
<code>xsl:extension-element-prefixes</code> attribute;
a subtree rooted at an <code>xsl:stylesheet</code> element
does not include any stylesheets imported or included by children
of that <code>xsl:stylesheet</code> element.</p>

<p>If the XSLT processor does not have an implementation of a
particular extension element available, then the
<function>element-available</function> function must return false for
the name of the element.  When such an extension element is
instantiated, then the XSLT processor must perform fallback for the
element as specified in <specref ref="fallback"/>.  An XSLT processor
must not signal an error merely because a template contains an
extension element for which no implementation is available.</p>

<p>If the XSLT processor has an implementation of a particular
extension element available, then the
<function>element-available</function> function must return true for
the name of the element.</p>

</div2>

<div2>
<head>Extension Functions</head>

<p>If a <xnt href="&XPath;#NT-FunctionName">FunctionName</xnt> in a
<xnt href="&XPath;#NT-FunctionCall">FunctionCall</xnt> expression is
not an <xnt href="&XMLNames;#NT-NCName">NCName</xnt> (i.e. if it
contains a colon), then it is treated as a call to an extension
function.  The <xnt href="&XPath;#NT-FunctionName">FunctionName</xnt>
is expanded to a name using the namespace declarations from the
evaluation context.</p>

<p>If the XSLT processor does not have an implementation of an
extension function of a particular name available, then the
<function>function-available</function> function must return false for
that name.  If such an extension function occurs in an expression and
the extension function is actually called, the XSLT processor must
signal an error.  An XSLT processor must not signal an error merely
because an expression contains an extension function for which no
implementation is available.</p>

<p>If the XSLT processor has an implementation of an extension
function of a particular name available, then the
<function>function-available</function> function must return
true for that name. If such an extension is called, then the XSLT
processor must call the implementation passing it the function call
arguments; the result returned by the implementation is returned as
the result of the function call.</p>

</div2>

</div1>

<div1 id="fallback">
<head>Fallback</head>

<e:element-syntax name="fallback">
  <e:in-category name="instruction"/>
  <e:model name="template"/>
</e:element-syntax>

<p>Normally, instantiating an <code>xsl:fallback</code> element does
nothing.  However, when an XSLT processor performs fallback for an
instruction element, if the instruction element has one or more
<code>xsl:fallback</code> children, then the content of each of the
<code>xsl:fallback</code> children must be instantiated in sequence;
otherwise, an error must be signaled. The content of an
<code>xsl:fallback</code> element is a template.</p>

<p>The following functions can be used with the
<code>xsl:choose</code> and <code>xsl:if</code> instructions to
explicitly control how a stylesheet should behave if particular
elements or functions are not available.</p>

<proto name="element-available" return-type="boolean"><arg
type="string"/></proto>

<p>The argument must evaluate to a string that is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>.  The <xnt
href="&XMLNames;#NT-QName">QName</xnt> is expanded into an <xtermref
href="&XPath;#dt-expanded-name">expanded-name</xtermref> using the
namespace declarations in scope for the expression. The
<function>element-available</function> function returns true if and
only if the expanded-name is the name of an instruction.  If the
expanded-name has a namespace URI equal to the XSLT namespace URI,
then it refers to an element defined by XSLT.  Otherwise, it refers to
an extension element. If the expanded-name has a null namespace URI,
the <function>element-available</function> function will return
false.</p>

<proto name="function-available" return-type="boolean"><arg
type="string"/></proto>

<p>The argument must evaluate to a string that is a <xnt
href="&XMLNames;#NT-QName">QName</xnt>.  The <xnt
href="&XMLNames;#NT-QName">QName</xnt> is expanded into an <xtermref
href="&XPath;#dt-expanded-name">expanded-name</xtermref> using the
namespace declarations in scope for the expression. The
<function>function-available</function> function returns true if and
only if the expanded-name is the name of a function in the function
library. If the expanded-name has a non-null namespace URI, then it
refers to an extension function; otherwise, it refers to a function
defined by XPath or XSLT.</p>

</div1>

<div1 id="output">
<head>Output</head>

<e:element-syntax name="output">
  <e:in-category name="top-level-element"/>
  <e:attribute name="method">
    <e:constant value="xml"/>
    <e:constant value="html"/>
    <e:constant value="text"/>
    <e:data-type name="qname-but-not-ncname"/>
  </e:attribute>
  <e:attribute name="version">
    <e:data-type name="nmtoken"/>
  </e:attribute>
  <e:attribute name="encoding">
    <e:data-type name="string"/>
  </e:attribute>
  <e:attribute name="omit-xml-declaration">
    <e:constant value="yes"/>
    <e:constant value="no"/>
  </e:attribute>
  <e:attribute name="standalone">
    <e:constant value="yes"/>
    <e:constant value="no"/>
  </e:attribute>
  <e:attribute name="doctype-public">
    <e:data-type name="string"/>
  </e:attribute>
  <e:attribute name="doctype-system">
    <e:data-type name="string"/>
  </e:attribute>
  <e:attribute name="cdata-section-elements">
    <e:data-type name="qnames"/>
  </e:attribute>
  <e:attribute name="indent">
    <e:constant value="yes"/>
    <e:constant value="no"/>
  </e:attribute>
  <e:attribute name="media-type">
    <e:data-type name="string"/>
  </e:attribute>
  <e:empty/>
</e:element-syntax>

<p>An XSLT processor may output the result tree as a sequence of
bytes, although it is not required to be able to do so (see <specref
ref="conformance"/>). The <code>xsl:output</code> element allows
stylesheet authors to specify how they wish the result tree to be
output. If an XSLT processor outputs the result tree, it should do so
as specified by the <code>xsl:output</code> element; however, it is
not required to do so.</p>

<p>The <code>xsl:output</code> element is only allowed as a <termref
def="dt-top-level">top-level</termref> element.</p>

<p>The <code>method</code> attribute on <code>xsl:output</code>
identifies the overall method that should be used for outputting the
result tree.  The value must be a <xnt
href="&XMLNames;#NT-QName">QName</xnt>.  If the <xnt
href="&XMLNames;#NT-QName">QName</xnt> does not have a prefix, then it
identifies a method specified in this document and must be one of
<code>xml</code>, <code>html</code> or <code>text</code>.  If the <xnt
href="&XMLNames;#NT-QName">QName</xnt> has a prefix, then the <xnt
href="&XMLNames;#NT-QName">QName</xnt> is expanded into an <xtermref
href="&XPath;#dt-expanded-name">expanded-name</xtermref> as described
in <specref ref="qname"/>; the expanded-name identifies the output
method; the behavior in this case is not specified by this
document.</p>

<p>The default for the <code>method</code> attribute is chosen as
follows.  If</p>

<ulist>

<item><p>the root node of the result tree has an element
child,</p></item>

<item><p>the expanded-name of the first element child of the root node
(i.e. the document element) of the result tree has local part
<code>html</code> (in any combination of upper and lower case) and a
null namespace URI, and</p></item>

<item><p>any text nodes preceding the first element child of the root
node of the result tree contain only whitespace characters,</p></item>

</ulist>

<p>then the default output method is <code>html</code>; otherwise, the
default output method is <code>xml</code>.  The default output method
should be used if there are no <code>xsl:output</code> elements or if
none of the <code>xsl:output</code> elements specifies a value for the
<code>method</code> attribute.</p>

<p>The other attributes on <code>xsl:output</code> provide parameters
for the output method.  The following attributes are allowed:</p>

<ulist>

<item><p><code>version</code> specifies the version of the output
method</p></item>

<item><p><code>indent</code> specifies whether the XSLT processor may
add additional whitespace when outputting the result tree; the value
must be <code>yes</code> or <code>no</code></p></item>

<item><p><code>encoding</code> specifies the preferred character
encoding that the XSLT processor should use to encode sequences of
characters as sequences of bytes; the value of the attribute should be
treated case-insensitively; the value must contain only characters in
the range #x21 to #x7E (i.e. printable ASCII characters); the value
should either be a <code>charset</code> registered with the Internet
Assigned Numbers Authority <bibref ref="IANA"/>, <bibref
ref="RFC2278"/> or start with <code>X-</code></p></item>

<item><p><code>media-type</code> specifies the media type (MIME
content type) of the data that results from outputting the result
tree; the <code>charset</code> parameter should not be specified
explicitly; instead, when the top-level media type is
<code>text</code>, a <code>charset</code> parameter should be added
according to the character encoding actually used by the output
method</p></item>

<item><p><code>doctype-system</code> specifies the system identifier
to be used in the document type declaration</p></item>

<item><p><code>doctype-public</code> specifies the public identifier
to be used in the document type declaration</p></item>

<item><p><code>omit-xml-declaration</code> specifies whether the XSLT
processor should output an XML declaration; the value must be
<code>yes</code> or <code>no</code></p></item>

<item><p><code>standalone</code> specifies whether the XSLT processor
should output a standalone document declaration; the value must be
<code>yes</code> or <code>no</code></p></item>

<item><p><code>cdata-section-elements</code> specifies a list of the
names of elements whose text node children should be output using
CDATA sections</p></item>

</ulist>

<p>The detailed semantics of each attribute will be described
separately for each output method for which it is applicable.  If the
semantics of an attribute are not described for an output method, then
it is not applicable to that output method.</p>

<p>A stylesheet may contain multiple <code>xsl:output</code> elements
and may include or import stylesheets that also contain
<code>xsl:output</code> elements.  All the <code>xsl:output</code>
elements occurring in a stylesheet are merged into a single effective
<code>xsl:output</code> element. For the
<code>cdata-section-elements</code> attribute, the effective value is
the union of the specified values.  For other attributes, the
effective value is the specified value with the highest <termref
def="dt-import-precedence">import precedence</termref>. It is an error
if there is more than one such value for an attribute.  An XSLT
processor may signal the error; if it does not signal the error, if
should recover by using the value that occurs last in the stylesheet.
The values of attributes are defaulted after the
<code>xsl:output</code> elements have been merged; different output
methods may have different default values for an attribute.</p>

<div2>
<head>XML Output Method</head>

<p>The <code>xml</code> output method outputs the result tree as a
well-formed XML external general parsed entity. If the root node of
the result tree has a single element node child and no text node
children, then the entity should also be a well-formed XML document
entity. When the entity is referenced within a trivial XML document
wrapper like this</p>

<eg><![CDATA[
<!DOCTYPE doc [
<!ENTITY e SYSTEM "]]><var>entity-URI</var><![CDATA[">
]>
<doc>&e;</doc>]]></eg>

<p>where <code><var>entity-URI</var></code> is a URI for the entity,
then the wrapper
document as a whole should be a well-formed XML document conforming to
the XML Namespaces Recommendation <bibref ref="XMLNAMES"/>.  In
addition, the output should be such that if a new tree was constructed
by parsing the wrapper as an XML document as specified in <specref
ref="data-model"/>, and then removing the document element, making its
children instead be children of the root node, then the new tree would
be the same as the result tree, with the following possible
exceptions:</p>

<ulist>

<item><p>The order of attributes in the two trees may be
different.</p></item>

<item><p>The new tree may contain namespace nodes that were not
present in the result tree.</p>
<note><p>An XSLT processor may need to add
namespace declarations in the course of outputting the result tree as
XML.</p></note>
</item>

</ulist>

<p>If the XSLT processor generated a document type declaration because
of the <code>doctype-system</code> attribute, then the above
requirements apply to the entity with the generated document type
declaration removed.</p>

<p>The <code>version</code> attribute specifies the version of XML to
be used for outputting the result tree.  If the XSLT processor does
not support this version of XML, it should use a version of XML that
it does support.  The version output in the XML declaration (if an XML
declaration is output) should correspond to the version of XML that
the processor used for outputting the result tree. The value of the
<code>version</code> attribute should match the <xnt
href="&XML;#NT-VersionNum">VersionNum</xnt> production of the XML
Recommendation <bibref ref="XML"/>. The default value is
<code>1.0</code>.</p>

<p>The <code>encoding</code> attribute specifies the preferred
encoding to use for outputting the result tree.  XSLT processors are
required to respect values of <code>UTF-8</code> and
<code>UTF-16</code>.  For other values, if the XSLT processor does not
support the specified encoding it may signal an error; if it does not
signal an error it should use <code>UTF-8</code> or
<code>UTF-16</code> instead.  The XSLT processor must not use an
encoding whose name does not match the <xnt
href="&XML;#NT-EncName">EncName</xnt> production of the XML
Recommendation <bibref ref="XML"/>.  If no <code>encoding</code>
attribute is specified, then the XSLT processor should use either
<code>UTF-8</code> or <code>UTF-16</code>.  It is possible that the
result tree will contain a character that cannot be represented in the
encoding that the XSLT processor is using for output.  In this case,
if the character occurs in a context where XML recognizes character
references (i.e. in the value of an attribute node or text node), then
the character should be output as a character reference; otherwise
(for example if the character occurs in the name of an element) the
XSLT processor should signal an error.</p>

<p>If the <code>indent</code> attribute has the value
<code>yes</code>, then the <code>xml</code> output method may output
whitespace in addition to the whitespace in the result tree (possibly
based on whitespace stripped from either the source document or the
stylesheet) in order to indent the result nicely; if the
<code>indent</code> attribute has the value <code>no</code>, it should
not output any additional whitespace. The default value is
<code>no</code>.  The <code>xml</code> output method should use an
algorithm to output additional whitespace that ensures that the result
if whitespace were to be stripped from the output using the process
described in <specref ref="strip"/> with the set of
whitespace-preserving elements consisting of just
<code>xsl:text</code> would be the same when additional whitespace is
output as when additional whitespace is not output.</p>

<note><p>It is usually not safe to use <code>indent="yes"</code> with
document types that include element types with mixed content.</p></note>

<p>The <code>cdata-section-elements</code> attribute contains a
whitespace-separated list of <xnt
href="&XMLNames;#NT-QName">QName</xnt>s.  Each <xnt
href="&XMLNames;#NT-QName">QName</xnt> is expanded into an
expanded-name using the namespace declarations in effect on the
<code>xsl:output</code> element in which the <xnt
href="&XMLNames;#NT-QName">QName</xnt> occurs; if there is a default
namespace, it is used for <xnt href="&XMLNames;#NT-QName">QName</xnt>s
that do not have a prefix.  The expansion is performed before the
merging of multiple <code>xsl:output</code> elements into a single
effective <code>xsl:output</code> element. If the expanded-name of the
parent of a text node is a member of the list, then the text node
should be output as a CDATA section. For example,</p>

<eg><![CDATA[<xsl:output cdata-section-elements="example"/>]]></eg>

<p>would cause a literal result element written in the stylesheet as</p>

<eg><![CDATA[<example>&lt;foo></example>]]></eg>

<p>or as</p>

<eg>&lt;example>&lt;![CDATA[&lt;foo>]]&gt;&lt;/example></eg>

<p>to be output as</p>

<eg>&lt;example>&lt;![CDATA[&lt;foo>]]&gt;&lt;/example></eg>

<p>If the text node contains the sequence of characters
<code>]]&gt;</code>, then the currently open CDATA section should be
closed following the <code>]]</code> and a new CDATA section opened
before the <code>&gt;</code>. For example, a literal result element
written in the stylesheet as</p>

<eg>&lt;example&gt;]]&amp;gt;&lt;/example&gt;</eg>

<p>would be output as</p>

<eg>&lt;example&gt;&lt;![CDATA[]]]]&gt;&lt;![CDATA[&gt;]]&gt;&lt;/example&gt;</eg>

<p>If the text node contains a character that is not representable in
the character encoding being used to output the result tree, then the
currently open CDATA section should be closed before the character,
the character should be output using a character reference or entity
reference, and a new CDATA section should be opened for any further
characters in the text node.</p>

<p>CDATA sections should not be used except for text nodes that the
<code>cdata-section-elements</code> attribute explicitly specifies
should be output using CDATA sections.</p>

<p>The <code>xml</code> output method should output an XML declaration
unless the <code>omit-xml-declaration</code> attribute has the value
<code>yes</code>. The XML declaration should include both version
information and an encoding declaration. If the
<code>standalone</code> attribute is specified, it should include a
standalone document declaration with the same value as the value as
the value of the <code>standalone</code> attribute.  Otherwise, it
should not include a standalone document declaration; this ensures
that it is both a XML declaration (allowed at the beginning of a
document entity) and a text declaration (allowed at the beginning of
an external general parsed entity).</p>

<p>If the <code>doctype-system</code> attribute is specified, the
<code>xml</code> output method should output a document type
declaration immediately before the first element.  The name following
<code>&lt;!DOCTYPE</code> should be the name of the first element.  If
<code>doctype-public</code> attribute is also specified, then the
<code>xml</code> output method should output <code>PUBLIC</code>
followed by the public identifier and then the system identifier;
otherwise, it should output <code>SYSTEM</code> followed by the system
identifier.  The internal subset should be empty.  The
<code>doctype-public</code> attribute should be ignored unless the
<code>doctype-system</code> attribute is specified.</p>

<p>The <code>media-type</code> attribute is applicable for the
<code>xml</code> output method.  The default value for the
<code>media-type</code> attribute is <code>text/xml</code>.</p>

</div2>

<div2>
<head>HTML Output Method</head>

<p>The <code>html</code> output method outputs the result tree as
HTML; for example,</p>

<eg>&lt;xsl:stylesheet version="1.0"
                xmlns:xsl="&XSLT.ns;"><![CDATA[

<xsl:output method="html"/>

<xsl:template match="/">
  <html>
   <xsl:apply-templates/>
  </html>
</xsl:template>

...

</xsl:stylesheet>]]></eg>

<p>The <code>version</code> attribute indicates the version of the
HTML.  The default value is <code>4.0</code>, which specifies that the
result should be output as HTML conforming to the HTML 4.0
Recommendation <bibref ref="HTML"/>.</p>

<p>The <code>html</code> output method should not output an element
differently from the <code>xml</code> output method unless the
expanded-name of the element has a null namespace URI; an element
whose expanded-name has a non-null namespace URI should be output as
XML.  If the expanded-name of the element has a null namespace URI,
but the local part of the expanded-name is not recognized as the name
of an HTML element, the element should output in the same way as a
non-empty, inline element such as <code>span</code>.</p>

<p>The <code>html</code> output method should not output an end-tag
for empty elements.  For HTML 4.0, the empty elements are
<code>area</code>, <code>base</code>, <code>basefont</code>,
<code>br</code>, <code>col</code>, <code>frame</code>,
<code>hr</code>, <code>img</code>, <code>input</code>,
<code>isindex</code>, <code>link</code>, <code>meta</code> and
<code>param</code>. For example, an element written as
<code>&lt;br/></code> or <code>&lt;br>&lt;/br></code> in the
stylesheet should be output as <code>&lt;br></code>.</p>

<p>The <code>html</code> output method should recognize the names of
HTML elements regardless of case.  For example, elements named
<code>br</code>, <code>BR</code> or <code>Br</code> should all be
recognized as the HTML <code>br</code> element and output without an
end-tag.</p>

<p>The <code>html</code> output method should not perform escaping for
the content of the <code>script</code> and <code>style</code>
elements. For example, a literal result element written in the
stylesheet as</p>

<eg><![CDATA[<script>if (a &lt; b) foo()</script>]]></eg>

<p>or</p>

<eg><![CDATA[<script><![CDATA[if (a < b) foo()]]]]><![CDATA[></script>]]></eg>

<p>should be output as</p>

<eg><![CDATA[<script>if (a < b) foo()</script>]]></eg>

<p>The <code>html</code> output method should not escape
<code>&lt;</code> characters occurring in attribute values.</p>

<p>If the <code>indent</code> attribute has the value
<code>yes</code>, then the <code>html</code> output method may add or
remove whitespace as it outputs the result tree, so long as it does
not change how an HTML user agent would render the output.  The
default value is <code>yes</code>.</p>

<p>The <code>html</code> output method should escape non-ASCII
characters in URI attribute values using the method recommended in
<loc
href="http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1">Section
B.2.1</loc> of the HTML 4.0 Recommendation.</p>

<p>The <code>html</code> output method may output a character using a
character entity reference, if one is defined for it in the version of
HTML that the output method is using.</p>

<p>The <code>html</code> output method should terminate processing
instructions with <code>&gt;</code> rather than
<code>?&gt;</code>.</p>

<p>The <code>html</code> output method should output boolean
attributes (that is attributes with only a single allowed value that
is equal to the name of the attribute) in minimized form. For example,
a start-tag written in the stylesheet as</p>

<eg><![CDATA[<OPTION selected="selected">]]></eg>

<p>should be output as</p>

<eg><![CDATA[<OPTION selected>]]></eg>

<p>The <code>html</code> output method should not escape a
<code>&amp;</code> character occurring in an attribute value
immediately followed by a <code>{</code> character (see <loc
href="http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.7.1.1">Section
B.7.1</loc> of the HTML 4.0 Recommendation). For example, a start-tag
written in the stylesheet as</p>

<eg><![CDATA[<BODY bgcolor='&amp;{{randomrbg}};'>]]></eg>

<p>should be output as</p>

<eg><![CDATA[<BODY bgcolor='&{randomrbg};'>]]></eg>

<p>The <code>encoding</code> attribute specifies the preferred
encoding to be used. If there is a <code>HEAD</code> element, then the
<code>html</code> output method should add a <code>META</code> element
immediately after the start-tag of the <code>HEAD</code> element
specifying the character encoding actually used. For example,</p>

<eg><![CDATA[<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=EUC-JP">
...]]></eg>

<p>It is possible that the result tree will contain a character that
cannot be represented in the encoding that the XSLT processor is using
for output.  In this case, if the character occurs in a context where
HTML recognizes character references, then the character should be
output as a character entity reference or decimal numeric character
reference; otherwise (for example, in a
<code>script</code> or <code>style</code> element or in a comment),
the XSLT processor should signal an error.</p>

<p>If the <code>doctype-public</code> or <code>doctype-system</code>
attributes are specified, then the <code>html</code> output method
should output a document type declaration immediately before the first
element.  The name following <code>&lt;!DOCTYPE</code> should be
<code>HTML</code> or <code>html</code>.  If the
<code>doctype-public</code> attribute is specified, then the output
method should output <code>PUBLIC</code> followed by the specified
public identifier; if the <code>doctype-system</code> attribute is
also specified, it should also output the specified system identifier
following the public identifier.  If the <code>doctype-system</code>
attribute is specified but the <code>doctype-public</code> attribute
is not specified, then the output method should output
<code>SYSTEM</code> followed by the specified system identifier.</p>

<p>The <code>media-type</code> attribute is applicable for the
<code>html</code> output method.  The default value is
<code>text/html</code>.</p>

</div2>

<div2>
<head>Text Output Method</head>

<p>The <code>text</code> output method outputs the result tree by
outputting the string-value of every text node in the result tree in
document order without any escaping.</p>

<p>The <code>media-type</code> attribute is applicable for the
<code>text</code> output method.  The default value for the
<code>media-type</code> attribute is <code>text/plain</code>.</p>

<p>The <code>encoding</code> attribute identifies the encoding that
the <code>text</code> output method should use to convert sequences of
characters to sequences of bytes.  The default is system-dependent. If
the result tree contains a character that cannot be represented in the
encoding that the XSLT processor is using for output, the XSLT
processor should signal an error.</p>

</div2>

<div2 id="disable-output-escaping">
<head>Disabling Output Escaping</head>

<p>Normally, the <code>xml</code> output method escapes &amp; and &lt;
(and possibly other characters) when outputting text nodes.  This
ensures that the output is well-formed XML. However, it is sometimes
convenient to be able to produce output that is almost, but not quite
well-formed XML; for example, the output may include ill-formed
sections which are intended to be transformed into well-formed XML by
a subsequent non-XML aware process.  For this reason, XSLT provides a
mechanism for disabling output escaping. An <code>xsl:value-of</code>
or <code>xsl:text</code> element may have a
<code>disable-output-escaping</code> attribute; the allowed values are
<code>yes</code> or <code>no</code>; the default is <code>no</code>;
if the value is <code>yes</code>, then a text node generated by
instantiating the <code>xsl:value-of</code> or <code>xsl:text</code>
element should be output without any escaping. For example,</p>

<eg><![CDATA[<xsl:text disable-output-escaping="yes">&lt;</xsl:text>]]></eg>

<p>should generate the single character <code>&lt;</code>.</p>

<p>It is an error for output escaping to be disabled for a text node
that is used for something other than a text node in the result tree.
Thus, it is an error to disable output escaping for an
<code>xsl:value-of</code> or <code>xsl:text</code> element that is
used to generate the string-value of a comment, processing instruction
or attribute node; it is also an error to convert a <termref
def="dt-result-tree-fragment">result tree fragment</termref> to a
number or a string if the result tree fragment contains a text node for
which escaping was disabled.  In both cases, an XSLT processor may
signal the error; if it does not signal the error, it must recover by
ignoring the <code>disable-output-escaping</code> attribute.</p>

<p>The <code>disable-output-escaping</code> attribute may be used with
the <code>html</code> output method as well as with the
<code>xml</code> output method.  The <code>text</code> output method
ignores the <code>disable-output-escaping</code> attribute, since it
does not perform any output escaping.</p>

<p>An XSLT processor will only be able to disable output escaping if
it controls how the result tree is output. This may not always be the
case.  For example, the result tree may be used as the source tree for
another XSLT transformation instead of being output.  An XSLT
processor is not required to support disabling output escaping.  If an
<code>xsl:value-of</code> or <code>xsl:text</code> specifies that
output escaping should be disabled and the XSLT processor does not
support this, the XSLT processor may signal an error; if it does not
signal an error, it must recover by not disabling output escaping.</p>

<p>If output escaping is disabled for a character that is not
representable in the encoding that the XSLT processor is using for
output, then the XSLT processor may signal an error; if it does not
signal an error, it must recover by not disabling output escaping.</p>

<p>Since disabling output escaping may not work with all XSLT
processors and can result in XML that is not well-formed, it should be
used only when there is no alternative.</p>


</div2>

</div1>

<div1 id="conformance">
<head>Conformance</head>

<p>A conforming XSLT processor must be able to use a stylesheet to
transform a source tree into a result tree as specified in this
document.  A conforming XSLT processor need not be able to output the
result in XML or in any other form.</p>

<note><p>Vendors of XSLT processors are strongly encouraged to provide
a way to verify that their processor is behaving conformingly by
allowing the result tree to be output as XML or by providing access to
the result tree through a standard API such as the DOM or
SAX.</p></note>

<p>A conforming XSLT processor must signal any errors except for those
that this document specifically allows an XSLT processor not to
signal. A conforming XSLT processor may but need not recover from any
errors that it signals.</p>

<p>A conforming XSLT processor may impose limits on the processing
resources consumed by the processing of a stylesheet.</p>

</div1>

<div1 id="notation">
<head>Notation</head>

<p>The specification of each XSLT-defined element type is preceded by
a summary of its syntax in the form of a model for elements of that
element type.  The meaning of syntax summary notation is as
follows:</p>

<ulist>

<item><p>An attribute is required if and only if its name is in
bold.</p></item>

<item><p>The string that occurs in the place of an attribute value
specifies the allowed values of the attribute.  If this is surrounded
by curly braces, then the attribute value is treated as an <termref
def="dt-attribute-value-template">attribute value template</termref>,
and the string occurring within curly braces specifies the allowed
values of the result of instantiating the attribute value template.
Alternative allowed values are separated by <code>|</code>.  A quoted
string indicates a value equal to that specific string. An unquoted,
italicized name specifies a particular type of value.</p></item>

<item><p>If the element is allowed not to be empty, then the element
contains a comment specifying the allowed content.  The allowed
content is specified in a similar way to an element type declaration
in XML; <emph>template</emph> means that any mixture of text nodes,
literal result elements, extension elements, and XSLT elements from
the <code>instruction</code> category is allowed;
<emph>top-level-elements</emph> means that any mixture of XSLT
elements from the <code>top-level-element</code> category is
allowed.</p></item>

<item><p>The element is prefaced by comments indicating if it belongs
to the <code>instruction</code> category or
<code>top-level-element</code> category or both.  The category of an
element just affects whether it is allowed in the content of elements
that allow a <emph>template</emph> or
<emph>top-level-elements</emph>.</p></item>

</ulist>

</div1>

</body>

<back>
<div1>
<head>References</head>
<div2>
<head>Normative References</head>

<blist>

<bibl id="XML" key="XML">World Wide Web Consortium. <emph>Extensible
Markup Language (XML) 1.0.</emph> W3C Recommendation. See <loc
href="http://www.w3.org/TR/1998/REC-xml-19980210">http://www.w3.org/TR/1998/REC-xml-19980210</loc></bibl>

<bibl id="XMLNAMES" key="XML Names">World Wide Web
Consortium. <emph>Namespaces in XML.</emph> W3C Recommendation. See
<loc
href="http://www.w3.org/TR/REC-xml-names">http://www.w3.org/TR/REC-xml-names</loc></bibl>

<bibl id="XPATH" key="XPath">World Wide Web Consortium. <emph>XML Path
Language.</emph> W3C Recommendation. See <loc
href="&XPath;">http://www.w3.org/TR/xpath</loc></bibl>

</blist>
</div2>
<div2>
<head>Other References</head>

<blist>

<bibl id="CSS2" key="CSS2">World Wide Web Consortium.  <emph>Cascading
Style Sheets, level 2 (CSS2)</emph>.  W3C Recommendation.  See <loc
href="http://www.w3.org/TR/1998/REC-CSS2-19980512"
>http://www.w3.org/TR/1998/REC-CSS2-19980512</loc></bibl>

<bibl id="DSSSL" key="DSSSL">International Organization
for Standardization, International Electrotechnical Commission.
<emph>ISO/IEC 10179:1996.  Document Style Semantics and Specification
Language (DSSSL)</emph>.  International Standard.</bibl>

<bibl id="HTML" key="HTML">World Wide Web Consortium. <emph>HTML 4.0
specification</emph>. W3C Recommendation. See <loc
href="http://www.w3.org/TR/REC-html40"
>http://www.w3.org/TR/REC-html40</loc></bibl>

<bibl id="IANA" key="IANA">Internet Assigned Numbers
Authority. <emph>Character Sets</emph>. See <loc
href="ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets"
>ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets</loc>.</bibl>

<bibl id="RFC2278" key="RFC2278">N. Freed, J. Postel.  <emph>IANA
Charset Registration Procedures</emph>.  IETF RFC 2278. See <loc
href="http://www.ietf.org/rfc/rfc2278.txt"
>http://www.ietf.org/rfc/rfc2278.txt</loc>.</bibl>

<bibl id="RFC2376" key="RFC2376">E. Whitehead, M. Murata.  <emph>XML
Media Types</emph>. IETF RFC 2376. See <loc
href="http://www.ietf.org/rfc/rfc2376.txt"
>http://www.ietf.org/rfc/rfc2376.txt</loc>.</bibl>

<bibl id="RFC2396" key="RFC2396">T. Berners-Lee, R. Fielding, and
L. Masinter.  <emph>Uniform Resource Identifiers (URI): Generic
Syntax</emph>. IETF RFC 2396. See <loc
href="http://www.ietf.org/rfc/rfc2396.txt">http://www.ietf.org/rfc/rfc2396.txt</loc>.</bibl>

<bibl id="UNICODE-TR10" key="UNICODE TR10">Unicode Consortium.
<emph>Unicode Technical Report #10. Unicode Collation
Algorithm</emph>.  Unicode Technical Report.  See <loc
href="http://www.unicode.org/unicode/reports/tr10/index.html"
>http://www.unicode.org/unicode/reports/tr10/index.html</loc>.</bibl>

<bibl id="XHTML" key="XHTML">World Wide Web Consortium. <emph>XHTML
1.0: The Extensible HyperText Markup Language.</emph> W3C Proposed
Recommendation. See <loc href="http://www.w3.org/TR/xhtml1"
>http://www.w3.org/TR/xhtml1</loc></bibl>

<bibl id="XPTR" key="XPointer">World Wide Web
Consortium. <emph>XML Pointer Language (XPointer).</emph> W3C Working
Draft. See <loc href="http://www.w3.org/TR/xptr"
>http://www.w3.org/TR/xptr</loc></bibl>

<bibl id="XMLSTYLE" key="XML Stylesheet">World Wide Web
Consortium. <emph>Associating stylesheets with XML documents.</emph>
W3C Recommendation. See <loc
href="http://www.w3.org/TR/xml-stylesheet"
>http://www.w3.org/TR/xml-stylesheet</loc></bibl>

<bibl id="XSL" key="XSL">World Wide Web Consortium.  <emph>Extensible
Stylesheet Language (XSL).</emph>  W3C Working Draft.  See <loc
href="http://www.w3.org/TR/WD-xsl"
     >http://www.w3.org/TR/WD-xsl</loc></bibl>

</blist>

</div2>
</div1>

<div1 id="element-syntax-summary">
<head>Element Syntax Summary</head>

<e:element-syntax-summary/>

</div1>

<inform-div1 id="dtd">
<head>DTD Fragment for XSLT Stylesheets</head>

<note><p>This DTD Fragment is not normative because XML 1.0 DTDs do
not support XML Namespaces and thus cannot correctly describe the
allowed structure of an XSLT stylesheet.</p></note>

<p>The following entity can be used to construct a DTD for XSLT
stylesheets that create instances of a particular result DTD.  Before
referencing the entity, the stylesheet DTD must define a
<code>result-elements</code> parameter entity listing the allowed
result element types.  For example:</p>

<eg><![CDATA[<!ENTITY % result-elements "
  | fo:inline-sequence
  | fo:block
">]]></eg>

<p>Such result elements should be declared to have
<code>xsl:use-attribute-sets</code> and
<code>xsl:extension-element-prefixes</code> attributes.  The following
entity declares the <code>result-element-atts</code> parameter for
this purpose. The content that XSLT allows for result elements is the
same as it allows for the XSLT elements that are declared in the
following entity with a content model of <code>%template;</code>.  The
DTD may use a more restrictive content model than
<code>%template;</code> to reflect the constraints of the result
DTD.</p>

<p>The DTD may define the <code>non-xsl-top-level</code> parameter
entity to allow additional top-level elements from namespaces other
than the XSLT namespace.</p>

<p>The use of the <code>xsl:</code> prefix in this DTD does not imply
that XSLT stylesheets are required to use this prefix.  Any of the
elements declared in this DTD may have attributes whose name starts
with <code>xmlns:</code> or is equal to <code>xmlns</code> in addition
to the attributes declared in this DTD.</p>

<eg><![CDATA[<!ENTITY % char-instructions "
  | xsl:apply-templates
  | xsl:call-template
  | xsl:apply-imports
  | xsl:for-each
  | xsl:value-of
  | xsl:copy-of
  | xsl:number
  | xsl:choose
  | xsl:if
  | xsl:text
  | xsl:copy
  | xsl:variable
  | xsl:message
  | xsl:fallback
">

<!ENTITY % instructions "
  %char-instructions;
  | xsl:processing-instruction
  | xsl:comment
  | xsl:element
  | xsl:attribute
">

<!ENTITY % char-template "
 (#PCDATA
  %char-instructions;)*
">

<!ENTITY % template "
 (#PCDATA
  %instructions;
  %result-elements;)*
">

<!-- Used for the type of an attribute value that is a URI reference.-->
<!ENTITY % URI "CDATA">

<!-- Used for the type of an attribute value that is a pattern.-->
<!ENTITY % pattern "CDATA">

<!-- Used for the type of an attribute value that is an
     attribute value template.-->
<!ENTITY % avt "CDATA">

<!-- Used for the type of an attribute value that is a QName; the prefix
     gets expanded by the XSLT processor. -->
<!ENTITY % qname "NMTOKEN">

<!-- Like qname but a whitespace-separated list of QNames. -->
<!ENTITY % qnames "NMTOKENS">

<!-- Used for the type of an attribute value that is an expression.-->
<!ENTITY % expr "CDATA">

<!-- Used for the type of an attribute value that consists
     of a single character.-->
<!ENTITY % char "CDATA">

<!-- Used for the type of an attribute value that is a priority. -->
<!ENTITY % priority "NMTOKEN">

<!ENTITY % space-att "xml:space (default|preserve) #IMPLIED">

<!-- This may be overridden to customize the set of elements allowed
at the top-level. -->

<!ENTITY % non-xsl-top-level "">

<!ENTITY % top-level "
 (xsl:import*,
  (xsl:include
  | xsl:strip-space
  | xsl:preserve-space
  | xsl:output
  | xsl:key
  | xsl:decimal-format
  | xsl:attribute-set
  | xsl:variable
  | xsl:param
  | xsl:template
  | xsl:namespace-alias
  %non-xsl-top-level;)*)
">

<!ENTITY % top-level-atts '
  extension-element-prefixes CDATA #IMPLIED
  exclude-result-prefixes CDATA #IMPLIED
  id ID #IMPLIED
  version NMTOKEN #REQUIRED
  xmlns:xsl CDATA #FIXED "]]>&XSLT.ns;<![CDATA["
  %space-att;
'>

<!-- This entity is defined for use in the ATTLIST declaration
for result elements. -->

<!ENTITY % result-element-atts '
  xsl:extension-element-prefixes CDATA #IMPLIED
  xsl:exclude-result-prefixes CDATA #IMPLIED
  xsl:use-attribute-sets %qnames; #IMPLIED
  xsl:version NMTOKEN #IMPLIED
'>

<!ELEMENT xsl:stylesheet %top-level;>
<!ATTLIST xsl:stylesheet %top-level-atts;>

<!ELEMENT xsl:transform %top-level;>
<!ATTLIST xsl:transform %top-level-atts;>

<!ELEMENT xsl:import EMPTY>
<!ATTLIST xsl:import href %URI; #REQUIRED>

<!ELEMENT xsl:include EMPTY>
<!ATTLIST xsl:include href %URI; #REQUIRED>

<!ELEMENT xsl:strip-space EMPTY>
<!ATTLIST xsl:strip-space elements CDATA #REQUIRED>

<!ELEMENT xsl:preserve-space EMPTY>
<!ATTLIST xsl:preserve-space elements CDATA #REQUIRED>

<!ELEMENT xsl:output EMPTY>
<!ATTLIST xsl:output
  method %qname; #IMPLIED
  version NMTOKEN #IMPLIED
  encoding CDATA #IMPLIED
  omit-xml-declaration (yes|no) #IMPLIED
  standalone (yes|no) #IMPLIED
  doctype-public CDATA #IMPLIED
  doctype-system CDATA #IMPLIED
  cdata-section-elements %qnames; #IMPLIED
  indent (yes|no) #IMPLIED
  media-type CDATA #IMPLIED
>

<!ELEMENT xsl:key EMPTY>
<!ATTLIST xsl:key
  name %qname; #REQUIRED
  match %pattern; #REQUIRED
  use %expr; #REQUIRED
>

<!ELEMENT xsl:decimal-format EMPTY>
<!ATTLIST xsl:decimal-format
  name %qname; #IMPLIED
  decimal-separator %char; "."
  grouping-separator %char; ","
  infinity CDATA "Infinity"
  minus-sign %char; "-"
  NaN CDATA "NaN"
  percent %char; "%"
  per-mille %char; "&#x2030;"
  zero-digit %char; "0"
  digit %char; "#"
  pattern-separator %char; ";"
>

<!ELEMENT xsl:namespace-alias EMPTY>
<!ATTLIST xsl:namespace-alias
  stylesheet-prefix CDATA #REQUIRED
  result-prefix CDATA #REQUIRED
>

<!ELEMENT xsl:template
 (#PCDATA
  %instructions;
  %result-elements;
  | xsl:param)*
>

<!ATTLIST xsl:template
  match %pattern; #IMPLIED
  name %qname; #IMPLIED
  priority %priority; #IMPLIED
  mode %qname; #IMPLIED
  %space-att;
>

<!ELEMENT xsl:value-of EMPTY>
<!ATTLIST xsl:value-of
  select %expr; #REQUIRED
  disable-output-escaping (yes|no) "no"
>

<!ELEMENT xsl:copy-of EMPTY>
<!ATTLIST xsl:copy-of select %expr; #REQUIRED>

<!ELEMENT xsl:number EMPTY>
<!ATTLIST xsl:number
   level (single|multiple|any) "single"
   count %pattern; #IMPLIED
   from %pattern; #IMPLIED
   value %expr; #IMPLIED
   format %avt; '1'
   lang %avt; #IMPLIED
   letter-value %avt; #IMPLIED
   grouping-separator %avt; #IMPLIED
   grouping-size %avt; #IMPLIED
>

<!ELEMENT xsl:apply-templates (xsl:sort|xsl:with-param)*>
<!ATTLIST xsl:apply-templates
  select %expr; "node()"
  mode %qname; #IMPLIED
>

<!ELEMENT xsl:apply-imports EMPTY>

<!-- xsl:sort cannot occur after any other elements or
any non-whitespace character -->

<!ELEMENT xsl:for-each
 (#PCDATA
  %instructions;
  %result-elements;
  | xsl:sort)*
>

<!ATTLIST xsl:for-each
  select %expr; #REQUIRED
  %space-att;
>

<!ELEMENT xsl:sort EMPTY>
<!ATTLIST xsl:sort
  select %expr; "."
  lang %avt; #IMPLIED
  data-type %avt; "text"
  order %avt; "ascending"
  case-order %avt; #IMPLIED
>

<!ELEMENT xsl:if %template;>
<!ATTLIST xsl:if
  test %expr; #REQUIRED
  %space-att;
>

<!ELEMENT xsl:choose (xsl:when+, xsl:otherwise?)>
<!ATTLIST xsl:choose %space-att;>

<!ELEMENT xsl:when %template;>
<!ATTLIST xsl:when
  test %expr; #REQUIRED
  %space-att;
>

<!ELEMENT xsl:otherwise %template;>
<!ATTLIST xsl:otherwise %space-att;>

<!ELEMENT xsl:attribute-set (xsl:attribute)*>
<!ATTLIST xsl:attribute-set
  name %qname; #REQUIRED
  use-attribute-sets %qnames; #IMPLIED
>

<!ELEMENT xsl:call-template (xsl:with-param)*>
<!ATTLIST xsl:call-template
  name %qname; #REQUIRED
>

<!ELEMENT xsl:with-param %template;>
<!ATTLIST xsl:with-param
  name %qname; #REQUIRED
  select %expr; #IMPLIED
>

<!ELEMENT xsl:variable %template;>
<!ATTLIST xsl:variable 
  name %qname; #REQUIRED
  select %expr; #IMPLIED
>

<!ELEMENT xsl:param %template;>
<!ATTLIST xsl:param 
  name %qname; #REQUIRED
  select %expr; #IMPLIED
>

<!ELEMENT xsl:text (#PCDATA)>
<!ATTLIST xsl:text
  disable-output-escaping (yes|no) "no"
>

<!ELEMENT xsl:processing-instruction %char-template;>
<!ATTLIST xsl:processing-instruction 
  name %avt; #REQUIRED
  %space-att;
>

<!ELEMENT xsl:element %template;>
<!ATTLIST xsl:element 
  name %avt; #REQUIRED
  namespace %avt; #IMPLIED
  use-attribute-sets %qnames; #IMPLIED
  %space-att;
>

<!ELEMENT xsl:attribute %char-template;>
<!ATTLIST xsl:attribute 
  name %avt; #REQUIRED
  namespace %avt; #IMPLIED
  %space-att;
>

<!ELEMENT xsl:comment %char-template;>
<!ATTLIST xsl:comment %space-att;>

<!ELEMENT xsl:copy %template;>
<!ATTLIST xsl:copy
  %space-att;
  use-attribute-sets %qnames; #IMPLIED
>

<!ELEMENT xsl:message %template;>
<!ATTLIST xsl:message
  %space-att;
  terminate (yes|no) "no"
>

<!ELEMENT xsl:fallback %template;>
<!ATTLIST xsl:fallback %space-att;>]]></eg>

</inform-div1>

<inform-div1>
<head>Examples</head>

<div2>
<head>Document Example</head>

<p>This example is a stylesheet for transforming documents that
conform to a simple DTD into XHTML <bibref ref="XHTML"/>.  The DTD
is:</p>

<eg><![CDATA[<!ELEMENT doc (title, chapter*)>
<!ELEMENT chapter (title, (para|note)*, section*)>
<!ELEMENT section (title, (para|note)*)>
<!ELEMENT title (#PCDATA|emph)*>
<!ELEMENT para (#PCDATA|emph)*>
<!ELEMENT note (#PCDATA|emph)*>
<!ELEMENT emph (#PCDATA|emph)*>]]></eg>

<p>The stylesheet is:</p>

<eg>&lt;xsl:stylesheet version="1.0"
                xmlns:xsl="&XSLT.ns;"
                xmlns="&XHTML.ns;"><![CDATA[

<xsl:strip-space elements="doc chapter section"/>
<xsl:output
   method="xml"
   indent="yes"
   encoding="iso-8859-1"
/>

<xsl:template match="doc">
 <html>
   <head>
     <title>
       <xsl:value-of select="title"/>
     </title>
   </head>
   <body>
     <xsl:apply-templates/>
   </body>
 </html>
</xsl:template>

<xsl:template match="doc/title">
  <h1>
    <xsl:apply-templates/>
  </h1>
</xsl:template>

<xsl:template match="chapter/title">
  <h2>
    <xsl:apply-templates/>
  </h2>
</xsl:template>

<xsl:template match="section/title">
  <h3>
    <xsl:apply-templates/>
  </h3>
</xsl:template>

<xsl:template match="para">
  <p>
    <xsl:apply-templates/>
  </p>
</xsl:template>

<xsl:template match="note">
  <p class="note">
    <b>NOTE: </b>
    <xsl:apply-templates/>
  </p>
</xsl:template>

<xsl:template match="emph">
  <em>
    <xsl:apply-templates/>
  </em>
</xsl:template>

</xsl:stylesheet>]]></eg>

<p>With the following input document</p>

<eg><![CDATA[<!DOCTYPE doc SYSTEM "doc.dtd">
<doc>
<title>Document Title</title>
<chapter>
<title>Chapter Title</title>
<section>
<title>Section Title</title>
<para>This is a test.</para>
<note>This is a note.</note>
</section>
<section>
<title>Another Section Title</title>
<para>This is <emph>another</emph> test.</para>
<note>This is another note.</note>
</section>
</chapter>
</doc>]]></eg>

<p>it would produce the following result</p>

<eg>&lt;?xml version="1.0" encoding="iso-8859-1"?>
&lt;html xmlns="&XHTML.ns;"><![CDATA[
<head>
<title>Document Title</title>
</head>
<body>
<h1>Document Title</h1>
<h2>Chapter Title</h2>
<h3>Section Title</h3>
<p>This is a test.</p>
<p class="note">
<b>NOTE: </b>This is a note.</p>
<h3>Another Section Title</h3>
<p>This is <em>another</em> test.</p>
<p class="note">
<b>NOTE: </b>This is another note.</p>
</body>
</html>]]></eg>

</div2>

<div2 id="data-example">
<head>Data Example</head>

<p>This is an example of transforming some data represented in XML
using three different XSLT stylesheets to produce three different
representations of the data, HTML, SVG and VRML.</p>

<p>The input data is:</p>

<eg><![CDATA[<sales>

        <division id="North">
                <revenue>10</revenue>
                <growth>9</growth>
                <bonus>7</bonus>
        </division>

        <division id="South">
                <revenue>4</revenue>
                <growth>3</growth>
                <bonus>4</bonus>
        </division>

        <division id="West">
                <revenue>6</revenue>
                <growth>-1.5</growth>
                <bonus>2</bonus>
        </division>

</sales>]]></eg>

<p>The following stylesheet, which uses the simplified syntax
described in <specref ref="result-element-stylesheet"/>, transforms
the data into HTML:</p>

<eg>&lt;html xsl:version="1.0"
      xmlns:xsl="&XSLT.ns;"<![CDATA[
      lang="en">
    <head>
	<title>Sales Results By Division</title>
    </head>
    <body>
	<table border="1">
	    <tr>
		<th>Division</th>
		<th>Revenue</th>
		<th>Growth</th>
		<th>Bonus</th>
	    </tr>
	    <xsl:for-each select="sales/division">
		<!-- order the result by revenue -->
		<xsl:sort select="revenue"
			  data-type="number"
			  order="descending"/>
		<tr>
		    <td>
			<em><xsl:value-of select="@id"/></em>
		    </td>
		    <td>
			<xsl:value-of select="revenue"/>
		    </td>
		    <td>
			<!-- highlight negative growth in red -->
			<xsl:if test="growth &lt; 0">
			     <xsl:attribute name="style">
				 <xsl:text>color:red</xsl:text>
			     </xsl:attribute>
			</xsl:if>
			<xsl:value-of select="growth"/>
		    </td>
		    <td>
			<xsl:value-of select="bonus"/>
		    </td>
		</tr>
	    </xsl:for-each>
	</table>
    </body>
</html>]]></eg>

<p>The HTML output is:</p>

<eg><![CDATA[<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Sales Results By Division</title>
</head>
<body>
<table border="1">
<tr>
<th>Division</th><th>Revenue</th><th>Growth</th><th>Bonus</th>
</tr>
<tr>
<td><em>North</em></td><td>10</td><td>9</td><td>7</td>
</tr>
<tr>
<td><em>West</em></td><td>6</td><td style="color:red">-1.5</td><td>2</td>
</tr>
<tr>
<td><em>South</em></td><td>4</td><td>3</td><td>4</td>
</tr>
</table>
</body>
</html>]]></eg>

<p>The following stylesheet transforms the data into SVG:</p>

<eg>&lt;xsl:stylesheet version="1.0"
                xmlns:xsl="&XSLT.ns;"<![CDATA[
                xmlns="http://www.w3.org/Graphics/SVG/SVG-19990812.dtd">

<xsl:output method="xml" indent="yes" media-type="image/svg"/>

<xsl:template match="/">

<svg width = "3in" height="3in">
    <g style = "stroke: #000000"> 
        <!-- draw the axes -->
        <line x1="0" x2="150" y1="150" y2="150"/>
        <line x1="0" x2="0" y1="0" y2="150"/>
        <text x="0" y="10">Revenue</text>
        <text x="150" y="165">Division</text>
        <xsl:for-each select="sales/division">
	    <!-- define some useful variables -->

	    <!-- the bar's x position -->
	    <xsl:variable name="pos"
	                  select="(position()*40)-30"/>

	    <!-- the bar's height -->
	    <xsl:variable name="height"
	                  select="revenue*10"/>

	    <!-- the rectangle -->
	    <rect x="{$pos}" y="{150-$height}"
                  width="20" height="{$height}"/>

	    <!-- the text label -->
	    <text x="{$pos}" y="165">
	        <xsl:value-of select="@id"/>
	    </text> 

	    <!-- the bar value -->
	    <text x="{$pos}" y="{145-$height}">
	        <xsl:value-of select="revenue"/>
	    </text>
        </xsl:for-each>
    </g>
</svg>

</xsl:template>
</xsl:stylesheet>]]></eg>

<p>The SVG output is:</p>

<eg><![CDATA[<svg width="3in" height="3in"
     xmlns="http://www.w3.org/Graphics/SVG/svg-19990412.dtd">
    <g style="stroke: #000000">
	<line x1="0" x2="150" y1="150" y2="150"/>
	<line x1="0" x2="0" y1="0" y2="150"/>
	<text x="0" y="10">Revenue</text>
	<text x="150" y="165">Division</text>
	<rect x="10" y="50" width="20" height="100"/>
	<text x="10" y="165">North</text>
	<text x="10" y="45">10</text>
	<rect x="50" y="110" width="20" height="40"/>
	<text x="50" y="165">South</text>
	<text x="50" y="105">4</text>
	<rect x="90" y="90" width="20" height="60"/>
	<text x="90" y="165">West</text>
	<text x="90" y="85">6</text>
    </g>
</svg>]]></eg>

<p>The following stylesheet transforms the data into VRML:</p>

<eg>&lt;xsl:stylesheet version="1.0"
                xmlns:xsl="&XSLT.ns;"><![CDATA[

<!-- generate text output as mime type model/vrml, using default charset -->
<xsl:output method="text" encoding="UTF-8" media-type="model/vrml"/>  

        <xsl:template match="/">#VRML V2.0 utf8 
 
# externproto definition of a single bar element 
EXTERNPROTO bar [ 
  field SFInt32 x  
  field SFInt32 y  
  field SFInt32 z  
  field SFString name  
  ] 
  "http://www.vrml.org/WorkingGroups/dbwork/barProto.wrl" 
 
# inline containing the graph axes 
Inline {  
        url "http://www.vrml.org/WorkingGroups/dbwork/barAxes.wrl" 
        } 
        
                <xsl:for-each select="sales/division">
bar {
        x <xsl:value-of select="revenue"/>
        y <xsl:value-of select="growth"/>
        z <xsl:value-of select="bonus"/>
        name "<xsl:value-of select="@id"/>" 
        }
                </xsl:for-each>
        
        </xsl:template> 
 
</xsl:stylesheet>]]></eg>

<p>The VRML output is:</p>

<eg><![CDATA[#VRML V2.0 utf8 
 
# externproto definition of a single bar element 
EXTERNPROTO bar [ 
  field SFInt32 x  
  field SFInt32 y  
  field SFInt32 z  
  field SFString name  
  ] 
  "http://www.vrml.org/WorkingGroups/dbwork/barProto.wrl" 
 
# inline containing the graph axes 
Inline {  
        url "http://www.vrml.org/WorkingGroups/dbwork/barAxes.wrl" 
        } 
        
                
bar {
        x 10
        y 9
        z 7
        name "North" 
        }
                
bar {
        x 4
        y 3
        z 4
        name "South" 
        }
                
bar {
        x 6
        y -1.5
        z 2
        name "West" 
        }]]></eg>

</div2>

</inform-div1>

<inform-div1>
<head>Acknowledgements</head>
<p>The following have contributed to authoring this draft:</p>
<slist>
<sitem>Daniel Lipkin, Saba</sitem>
<sitem>Jonathan Marsh, Microsoft</sitem>
<sitem>Henry Thompson, University of Edinburgh</sitem>
<sitem>Norman Walsh, Arbortext</sitem>
<sitem>Steve Zilles, Adobe</sitem>
</slist>

<p>This specification was developed and approved for publication by the
W3C XSL Working Group (WG). WG approval of this specification does not
necessarily imply that all WG members voted for its approval. The
current members of the XSL WG are:</p>

<orglist>
<member>
<name>Sharon Adler</name>
<affiliation>IBM</affiliation>
<role>Co-Chair</role>
</member>
<member>
<name>Anders Berglund</name>
<affiliation>IBM</affiliation>
</member>
<member>
<name>Perin Blanchard</name>
<affiliation>Novell</affiliation>
</member>
<member>
<name>Scott Boag</name>
<affiliation>Lotus</affiliation> 
</member>
<member>
<name>Larry Cable</name>
<affiliation>Sun</affiliation>
</member>
<member>
<name>Jeff Caruso</name>
<affiliation>Bitstream</affiliation>
</member>
<member>
<name>James Clark</name>
</member>
<member>
<name>Peter Danielsen</name>
<affiliation>Bell Labs</affiliation>
</member>
<member>
<name>Don Day</name>
<affiliation>IBM</affiliation>
</member>
<member>
<name>Stephen Deach</name>
<affiliation>Adobe</affiliation>
</member>
<member>
<name>Dwayne Dicks</name>
<affiliation>SoftQuad</affiliation>
</member>
<member>
<name>Andrew Greene</name>
<affiliation>Bitstream</affiliation>
</member>
<member>
<name>Paul Grosso</name>
<affiliation>Arbortext</affiliation>
</member>
<member>
<name>Eduardo Gutentag</name>
<affiliation>Sun</affiliation>
</member>
<member>
<name>Juliane Harbarth</name>
<affiliation>Software AG</affiliation>
</member>
<member>
<name>Mickey Kimchi</name>
<affiliation>Enigma</affiliation>
</member>
<member>
<name>Chris Lilley</name>
<affiliation>W3C</affiliation>
</member>
<member>
<name>Chris Maden</name>
<affiliation>Exemplary Technologies</affiliation>
</member>
<member>
<name>Jonathan Marsh</name>
<affiliation>Microsoft</affiliation>
</member>
<member>
<name>Alex Milowski</name> 
<affiliation>Lexica</affiliation>
</member>
<member>
<name>Steve Muench</name>
<affiliation>Oracle</affiliation>
</member>
<member>
<name>Scott Parnell</name>
<affiliation>Xerox</affiliation>
</member>
<member>
<name>Vincent Quint</name>
<affiliation>W3C</affiliation>
</member>
<member>
<name>Dan Rapp</name>
<affiliation>Novell</affiliation>
</member>
<member>
<name>Gregg Reynolds</name>
<affiliation>Datalogics</affiliation>
</member>
<member>
<name>Jonathan Robie</name>
<affiliation>Software AG</affiliation>
</member>
<member>
<name>Mark Scardina</name>
<affiliation>Oracle</affiliation>
</member>
<member>
<name>Henry Thompson</name>
<affiliation>University of Edinburgh</affiliation>
</member>
<member>
<name>Philip Wadler</name>
<affiliation>Bell Labs</affiliation>
</member>
<member>
<name>Norman Walsh</name>
<affiliation>Arbortext</affiliation>
</member>
<member>
<name>Sanjiva Weerawarana</name>
<affiliation>IBM</affiliation>
</member>
<member>
<name>Steve Zilles</name>
<affiliation>Adobe</affiliation>
<role>Co-Chair</role>
</member>
</orglist>

</inform-div1>

<inform-div1>
<head>Changes from Proposed Recommendation</head>

<p>The following are the changes since the Proposed Recommendation:</p>

<ulist>

<item><p>The <code>xsl:version</code> attribute is required on a
literal result element used as a stylesheet (see <specref
ref="result-element-stylesheet"/>).</p></item>

<item><p>The <code>data-type</code> attribute on <code>xsl:sort</code>
can use a prefixed name to specify a data-type not defined by
XSLT (see <specref ref="sorting"/>).</p></item>

</ulist>

</inform-div1>

<inform-div1>
<head>Features under Consideration for Future Versions of XSLT</head>

<p>The following features are under consideration for versions of XSLT
after XSLT 1.0:</p>

<ulist>

<item><p>a conditional expression;</p></item>

<item><p>support for XML Schema datatypes and archetypes;</p></item>

<item><p>support for something like style rules in the original XSL
submission;</p></item>

<item><p>an attribute to control the default namespace for names
occurring in XSLT attributes;</p></item>

<item><p>support for entity references;</p></item>

<item><p>support for DTDs in the data model;</p></item>

<item><p>support for notations in the data model;</p></item>

<item><p>a way to get back from an element to the elements that
reference it (e.g. by IDREF attributes);</p></item>

<item><p>an easier way to get an ID or key in another document;</p></item>

<item><p>support for regular expressions for matching against any or
all of text nodes, attribute values, attribute names, element type
names;</p></item>

<item><p>case-insensitive comparisons;</p></item>

<item><p>normalization of strings before comparison, for example for
compatibility characters;</p></item>

<item><p>a function <code>string resolve(node-set)</code> function
that treats the value of the argument as a relative URI and turns it
into an absolute URI using the base URI of the node;</p></item>

<item><p>multiple result documents;</p></item>

<item><p>defaulting the <code>select</code> attribute on
<code>xsl:value-of</code> to the current node;</p></item>

<item><p>an attribute on <code>xsl:attribute</code> to control how the
attribute value is normalized;</p></item>

<item><p>additional attributes on <code>xsl:sort</code> to provide
further control over sorting, such as relative order of
scripts;</p></item>

<item><p>a way to put the text of a resource identified by a URI into
the result tree;</p></item>

<item><p>allow unions in steps (e.g. <code>foo/(bar|baz)</code>);</p></item>

<item><p>allow for result tree fragments all operations that are
allowed for node-sets;</p></item>

<item><p>a way to group together consecutive nodes having duplicate
subelements or attributes;</p></item>

<item><p>features to make handling of the HTML <code>style</code>
attribute more convenient.</p></item>

</ulist>

</inform-div1>

</back>
</spec>
Added tests/data/books.xml.




























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?xml version='1.0'?>
<!-- Example from XQL -->
<!-- This file represents a fragment of a book store inventory database -->
<bookstore specialty='novel'>
  <book style='autobiography'>
    <title>Seven Years in Trenton</title>
    <author>
      <first-name>Joe</first-name>
      <last-name>Bob</last-name>
      <award>Trenton Literary Review Honorable Mention</award>
    </author>
    <price>12</price>
  </book>
  <book style='textbook'>
    <title>History of Trenton</title>
    <author>
      <first-name>Mary</first-name>
      <last-name>Bob</last-name>
      <publication>
        Selected Short Stories of
        <first-name>Mary</first-name> <last-name>Bob</last-name>
      </publication>
    </author>
    <price>55</price>
  </book>
  <magazine style='glossy' frequency='monthly'>
    <title>Tracking Trenton</title>
    <price>2.50</price>
    <subscription price='24' per='year'/>
  </magazine>
  <book style='novel' id='myfave'>
    <title>Trenton Today, Trenton Tomorrow</title>
    <author>
      <first-name>Toni</first-name>
      <last-name>Bob</last-name>
      <degree from='Trenton U'>B.A.</degree>
      <degree from='Harvard'>Ph.D.</degree>
      <award>Pulizer</award>
      <publication>Still in Trenton</publication>
      <publication>Trenton Forever</publication>
    </author>
    <price intl='canada' exchange='0.7'>6.50</price>
    <excerpt>
      <p>It was a dark and stormy night.</p>
      <p>But then all nights in Trenton seem dark and
      stormy to someone who has gone through what
      <emph>I</emph> have.</p>
      <definition-list>
        <term>Trenton</term>
        <definition>misery</definition>
      </definition-list>
    </excerpt>
  </book>
  <my:book style='leather' price='29.50' xmlns:my='http://www.placeholder-name-here.com/schema/'>
    <my:title>Who's Who in Trenton</my:title>
    <my:author>Robert Bob</my:author>
  </my:book>
</bookstore>
<!-- End comment -->



Added tests/data/i18n_1.xml.


>
1
<test>абвгдежзий</test>
Added tests/data/xslt_1.xsl.


















>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">
  <xsl:variable name="����" select="'foo'"/>
  <xsl:template match="/">
      <xsl:value-of select="$����"/>
  </xsl:template>
</xsl:stylesheet>
Added tests/decls.test.






























































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# Features covered:  Declarations
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on markup declarations.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

catch {unset elements}
proc elementDecl {name cmodel} {
    set ::elements($name) $cmodel
}
catch {unset attrs}
proc attlistDecl {name attName type dfltValue isrequired} {
    lappend ::attrs($name/$attName) $type $isrequired $dfltValue
}
catch {unset entities}
proc entityDecl {name is_param value base systemId publicId notationName} {
    set ::entities($name) [list $is_param $value $base $systemId $publicId $notationName]
}
catch {unset cdata}
proc CData data {
    append ::cdata [string trim $data]
}

proc extRefH {base systemId publicId} {
    if {![regexp {^[a-zA-Z]+:/} $systemId]}  {
        regsub {^[a-zA-Z]+:} $base {} base
        set basedir [file dirname $base]
        set systemId "[set basedir]/[set systemId]"
    } else {
        regsub {^[a-zA-Z]+:} $systemId systemId
    }
    if {[catch {set fd [open $systemId]}]} {
        return -code error \
                -errorinfo "Failed to open external entity $systemId"
    }
    return [list channel $systemId $fd]
}

proc extRefHstr {base systemId publicId} {
    if {![regexp {^[a-zA-Z]+:/} $systemId]}  {
        regsub {^[a-zA-Z]+:} $base {} base
        set basedir [file dirname $base]
        set systemId "[set basedir]/[set systemId]"
    } else {
        regsub {^[a-zA-Z]+:} $systemId systemId
    }
    if {[catch {set fd [open $systemId]}]} {
        return -code error \
                -errorinfo "Failed to open external entity $systemId"
    }
    return [list string  $systemId [read $fd [file size $systemId]]]
}


# Internal DTD subset

test decls-1.1 {element declaration} {
    catch {unset ::elements}
    array set ::elements {}

    catch {rename xml::decls-1.1 {}}
    set parser [xml::parser decls-1.1 \
	-elementdeclcommand elementDecl]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test [
<!ELEMENT Test (#PCDATA)>
]>
<Test></Test>
}

    array get ::elements
} {Test {MIXED {} {} {}}}

test decls-2.1 {attribute list declaration, implied} {
    catch {unset ::attrs}
    array set ::attrs {}

    catch {rename xml::decls-2.1 {}}
    set parser [xml::parser decls-2.1 \
	-attlistdeclcommand attlistDecl]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test [
<!ELEMENT Test (#PCDATA)>
<!ATTLIST Test
	test CDATA #IMPLIED>
]>
<Test test="value"/>}

    array get ::attrs
} {Test/test {CDATA 0 {}}}

test decls-2.2 {attribute list declaration, enum} {
    catch {unset ::attrs}
    array set ::attrs {}

    catch {rename xml::decls-2.2 {}}
    set parser [xml::parser decls-2.2 \
	-attlistdeclcommand attlistDecl]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test [
<!ELEMENT Test (#PCDATA)>
<!ATTLIST Test
	test (LGL|OTH) "LGL">
]>
<Test test="value"/>}

    array get ::attrs
} {Test/test {(LGL|OTH) 0 LGL}}

test decls-3.1 {entity declarations} {
    catch {unset ::entities}
    array set ::entities {}

    catch {rename xml::decls-3.1 {}}
    set parser [xml::parser decls-3.1 \
	-entitydeclcommand entityDecl]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test [
<!ENTITY testEnt "replacement text">
<!ELEMENT Test (#PCDATA)>
]>
<Test/>}

    array get ::entities
} {testEnt {0 {replacement text} {} {} {} {}}}

test decls-4.1 {parameter entity declarations} {
    catch {unset ::entities}
    array set ::entities {}
    catch {unset ::elements}
    array set ::elements {}

    catch {rename xml::decls-4.1 {}}
    set parser [xml::parser decls-4.1 \
            -paramentityparsing notstandalone \
            -elementdeclcommand elementDecl]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test [
<!ENTITY % PEnt "&#60;!ELEMENT Test (#PCDATA)&#62;">
%PEnt;
]>
<Test/>}

    array get ::elements
} {Test {MIXED {} {} {}}}

# NB. entity.test tests entity replacement as well

# External entities

test decls-5.1 {external entity} {
    catch {unset ::elements}
    array set ::elements {}

    catch {rename xml::decls-5.1 {}}
    set parser [xml::parser decls-5.1 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefH \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test SYSTEM "dtd-5.1.dtd">
<Test/>}

    array get ::elements
} {Test {MIXED {} {} {}}}

test decls-5.2 {external DTD subset} {
    catch {unset ::elements}
    array set ::elements {}
    catch {unset ::entities}
    array set ::entities {}

    catch {rename xml::decls-5.2 {}}
    set parser [xml::parser decls-5.2 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefH \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test SYSTEM "dtd-5.2.dtd">
<Test/>}

    array get ::elements
} {Test {MIXED {} {} {}}}

test decls-5.3 {external entity} {
    catch {unset ::elements}
    array set ::elements {}
    catch {unset ::entities}
    array set ::entities {}
    catch {unset ::externals}
    array set ::externals {}

    catch {rename xml::decls-5.3 {}}
    set parser [xml::parser decls-5.3 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefH \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test [
<!ENTITY % module SYSTEM "dtd-5.2.dtd">
%module;
]>
<Test/>}

    array get ::elements
} {Test {MIXED {} {} {}}}


test decls-5.4 {external entity} {
    catch {unset ::elements}
    array set ::elements {}

    catch {rename xml::decls-5.4 {}}
    set parser [xml::parser decls-5.4 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefHstr \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test SYSTEM "dtd-5.1.dtd">
<Test/>}

    array get ::elements
} {Test {MIXED {} {} {}}}

test decls-5.5 {external DTD subset} {
    catch {unset ::elements}
    array set ::elements {}
    catch {unset ::entities}
    array set ::entities {}

    catch {rename xml::decls-5.5 {}}
    set parser [xml::parser decls-5.5 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefHstr \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test SYSTEM "dtd-5.2.dtd">
<Test/>}

    array get ::elements
} {Test {MIXED {} {} {}}}


test decls-5.6 {external entity} {
    catch {unset ::elements}
    array set ::elements {}
    catch {unset ::entities}
    array set ::entities {}
    catch {unset ::externals}
    array set ::externals {}

    catch {rename xml::decls-5.6 {}}
    set parser [xml::parser decls-5.6 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefHstr \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test [
<!ENTITY % module SYSTEM "dtd-5.2.dtd">
%module;
]>
<Test/>}

    array get ::elements
} {Test {MIXED {} {} {}}}


# Conditional Sections

test decls-6.1 {conditional section: include} {
    catch {unset ::elements}
    array set ::elements {}

    catch {rename xml::decls-6.1 {}}
    set parser [xml::parser decls-6.1 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefH \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test SYSTEM "dtd-6.1.dtd">
<Test/>}

    array get ::elements
} {Test {MIXED {} {} {}}}

test decls-6.2 {conditional section: include, empty} {
    catch {unset ::elements}
    array set ::elements {}

    catch {rename xml::decls-6.2 {}}
    set parser [xml::parser decls-6.2 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefH \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test SYSTEM "dtd-6.2.dtd">
<Test/>}

    array get ::elements
} {}

test decls-6.3 {conditional section: include, empty} {
    catch {unset ::elements}
    array set ::elements {}

    catch {rename xml::decls-6.3 {}}
    set parser [xml::parser decls-6.3 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefH \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test SYSTEM "dtd-6.3.dtd">
<Test/>}

    array get ::elements
} {}

test decls-6.4 {conditional section: include, nested} {
    catch {unset ::elements}
    array set ::elements {}

    catch {rename xml::decls-6.4 {}}
    set parser [xml::parser decls-6.4 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefH \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test SYSTEM "dtd-6.4.dtd">
<Test/>}

    array size ::elements
} 3

test decls-6.6 {conditional section/PE combo} {
    catch {unset ::elements}
    array set ::elements {}

    catch {rename xml::decls-6.6 {}}
    set parser [xml::parser decls-6.6 \
            -paramentityparsing notstandalone \
            -externalentitycommand extRefH \
            -elementdeclcommand elementDecl \
            -baseurl file://[file join [pwd] decls.test]]
    $parser parse {<?xml version='1.0'?>
<!DOCTYPE Test SYSTEM "dtd-6.6.dtd">
<Test/>}

    array size ::elements
} 2

# Comments

# cleanup
::tcltest::cleanupTests
return
Added tests/doctype.test.






















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Features covered:  Document Type Declaration
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on Document Type Declarations.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1998-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

catch {unset result}
proc doctype {name pub system dtd} {
    lappend ::result $name $pub $system $dtd
}

test doctype-1.1 {Document Type Declaration: no internal DTD subset} {
    set ::result {}

    catch {rename xml::doctype-1.1 {}}
    set parser [xml::parser doctype-1.1 \
	-startdoctypedeclcommand doctype]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test></Test>
}
    set ::result
} {Test NULL NULL 0}

test doctype-2.1 {Document Type Declaration: internal DTD subset} {
    set ::result {}

    catch {rename xml::doctype-2.1 {}}
    set parser [xml::parser doctype-2.1 \
	-startdoctypedeclcommand doctype]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test [<!ELEMENT Test EMPTY>]>
<Test></Test>
}
    set ::result
} {Test NULL NULL 1}


# cleanup
::tcltest::cleanupTests
return
Added tests/dom.test.






















































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# Features covered: DOM functions
#
# This file contains a collection of tests for the DOM methods of
# tDOM.
# Tested commands and object commands:
# dom:
#    dom-1.*: createDocument, createDocumentNS
#    dom-2.*: parse
#
# Copyright (c) 2002 Rolf Ade.

if {[lsearch [namespace children] ::tcltest] == -1} {
    package require tcltest
    namespace import -force ::tcltest::*
}

if {[catch {package require tdom 0.7}]} {
   puts stderr "Cannot load tDOM 0.7 package"
   return
}

test dom-1.1 {createDocument with root node name not a XML Name} {
    list [catch {dom createDocument "root node"} msg] $msg
} "1 {invalid root element name}"

test dom-1.2 {createDocument with root node name not a XML Name} {
    list [catch {dom createDocument "1root"} msg] $msg
} "1 {invalid root element name}"

test dom-1.3 {createDocument - root name us-ascii} {
    dom createDocument "root" doc 
    set root [$doc documentElement]
    set result [$root nodeName]
    $doc delete
    set result
} "root"

test dom-1.4 {createDocument - root name with UTF-8 chars} {
    dom createDocument "\u00c4\u00d4\u00dc" doc 
    set root [$doc documentElement]
    set result [$root nodeName]
    $doc delete
    set result
} "\u00c4\u00d4\u00dc"
    
test dom-1.5 {createDocument with FQ root name} {
    dom createDocument "foo:bar" doc
    set root [$doc documentElement]
    set result [$root nodeName]
    $doc delete
    set result
} "foo:bar"

test dom-1.6 {createDocument with wrong # of args} {
    list [catch {dom createDocument "root" "http:/foo:bar" doc} msg] $msg
} "1 {wrong \# args: should be \"createDocument docElemName ?newObjVar?\"}"

test dom-1.7 {createDocumentNS - check root name} {
    set doc [dom createDocumentNS root "http://foo.bar"]
    set root [$doc documentElement]
    set result [$root nodeName]
    $doc delete
    set result
} "root"

test dom-1.8 {createDocumentNS - check the NS of the created root} {
    dom createDocumentNS root "http://foo.bar" doc
    set root [$doc documentElement]
    set result [$root namespaceURI]
    $doc delete
    set result
} "http://foo.bar"    

test dom-1.9 {createDocumentNS with root name not a NCName} {
    list [catch {dom createDocumentNS "foo bar" "http://foo.bar" doc} msg] $msg
} "1 {invalid local name}"

test dom-1.10 {createDocumentNS with root name not a NCName} {
    list [catch {dom createDocumentNS "a:b:c" "http://foo.bar" doc} msg] $msg
} "1 {invalid local name}"

test dom-1.11 {createDocumentNS with root name not a NCName} {
    list [catch {dom createDocumentNS "a b:b" "http://foo.bar" doc} msg] $msg
} "1 {invalid prefix name}"

test dom-1.12 {createDocumentNS with root name not a NCName} {
    list [catch {dom createDocumentNS "a:a b" "http://foo.bar" doc} msg] $msg
} "1 {invalid local name}"

test dom-1.13 {createDocumentNS - check root name} {
    set doc [dom createDocumentNS foo:root "http://foo.bar"]
    set root [$doc documentElement]
    set result [$root nodeName]
    $doc delete
    set result
} "foo:root"

test dom-2.1 {knownBug} {Don't quash white space at start or end of non white space content} {
    set doc [dom parse {<root>
    some content
    </root>}]
    set root [$doc documentElement]
    $root text
} {
    some content
    }

test dom-3.1 {knownBug} {repetitived createDocument with objVar, then delete} {
    dom createDocument "root" doc 
    $doc documentElement root
    $doc delete
    
    dom createDocument "\u00c4\u00d4\u00dc" doc 
    $doc documentElement root
    set result [$root nodeName]
    $doc delete
    set result
} "\u00c4\u00d4\u00dc"


# cleanup
::tcltest::cleanupTests
return
Added tests/domnamespace.test.






























>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

test domnamespace-1.1 {multiple definition of the same namespace (same prefix/uri)} {
    set ch [open data/REC-xslt-19991116.xml]
    fconfigure $ch -encoding iso8859-1
    set doc [dom parse -channel $ch]
    set root [$doc documentElement]
    set nodes [$root selectNodes //e:element-syntax]
    $doc delete
    llength $nodes
} {35}


# cleanup
::tcltest::cleanupTests
return
Added tests/element.test.




















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# Features covered:  Elements
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on elements.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1999-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

proc parray arrayName {
    upvar #0 $arrayName arr
    foreach key [lsort [array names $arrayName]] {
	lappend result $key $arr($key)
    }
    return $result
}

catch {unset started}
proc Start {name atList args} {
    array set opts $args
    if {![info exists ::started($name)]} {
	set ::started($name) 1
    } else {
	incr ::started($name)
    }
}
catch {unset ended}
proc End {name args} {
    array set opts $args
    if {![info exists ::ended($name)]} {
	set ::ended($name) 1
    } else {
	incr ::ended($name)
    }
}

catch {unset elList}
proc ElStart {name atList args} {
    array set opts {-empty 0}
    array set opts $args
    lappend ::elList start $name $opts(-empty)
}
proc ElEnd {name args} {
    array set opts {-empty 0}
    array set opts $args
    lappend ::elList end $name $opts(-empty)
}

test element-1.1 {document element} {
    catch {unset ::started}
    catch {unset ::ended}

    catch {rename xml::element-1.1 {}}
    set parser [xml::parser element-1.1 \
	-elementstartcommand Start \
	-elementendcommand End]
    $parser parse {<Test></Test>}
    list [array get ::started] [array get ::ended]
} {{Test 1} {Test 1}}

test element-1.2 {distinct elements} {
    catch {unset ::started}
    catch {unset ::ended}

    catch {rename xml::element-1.2 {}}
    set parser [xml::parser element-1.2 \
	-elementstartcommand Start \
	-elementendcommand End]
    $parser parse {<Test><Child1></Child1><Child2></Child2></Test>}
    list [parray ::started] [parray ::ended]
} {{Child1 1 Child2 1 Test 1} {Child1 1 Child2 1 Test 1}}

# cleanup
::tcltest::cleanupTests
return
Added tests/entity.test.




























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# Features covered:  Entities
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on entities.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1999-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

proc Start {name attrList args} {
    incr ::elements
}

proc pcdata text {
    append ::result $text
}

proc EntityRef name {
    lappend ::references $name
    append ::result ##entityreference##
    return {}
}

test entity-1.1 {parameter entity in document entity} {
    set ::result {}

    catch {rename xml::entity-1.1 {}}
    set parser [xml::parser entity-1.1 \
	-characterdatacommand pcdata]
    $parser parse {<!DOCTYPE Test [
<!ENTITY % Wrong "This is wrong">
]>
<Test>%wrong;</Test>}
    set ::result
} {%wrong;}

test entity-1.2 {character entities in hex} {
    set ::result {}

    catch {rename xml::entity-1.2 {}}
    set parser [xml::parser entity-1.2 \
	-characterdatacommand pcdata]
    $parser parse {<Test>&#x41;&#x3C;&#x3e;&#x24;&#x5B;&#x5D;</Test>}
    set ::result
} {A<>$[]}

test entity-1.3 {character entities in decimal} {
    set ::result {}

    catch {rename xml::entity-1.3 {}}
    set parser [xml::parser entity-1.3 \
	-characterdatacommand pcdata]
    $parser parse {<Test>&#65;&#60;&#62;&#36;&#91;&#93;</Test>}
    set ::result
} {A<>$[]}

test entity-1.4 {illegal character entity} {
    set ::result {}

    catch {rename xml::entity-1.4 {}}
    set parser [xml::parser entity-1.4 \
	-characterdatacommand pcdata]
    set err [catch {$parser parse {<Test>&#blah;</Test>}}]
    list $err $::result
} {1 {}}

test entity-2.1 {predefined general entities} {
    set ::result {}

    catch {rename xml::entity-2.1 {}}
    set parser [xml::parser entity-2.1 \
	-characterdatacommand pcdata]
    $parser parse {<Test>&lt;&gt;&amp;&quot;&apos;</Test>}
    set ::result
} {<>&"'}

# cleanup
::tcltest::cleanupTests
return
Added tests/i18n.test.






































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35


test i18n-1.1 {parse utf-8 string} {
    set russian "\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439"
    set doc [dom parse "<test>$russian</test>"]
    set root [$doc documentElement $doc]
    set text [$root text]
    $doc delete
    string compare $text "\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439"
} {0}

test i18n-1.2 {parse utf-8 channel } {
    set fd [open data/i18n_1.xml]
    fconfigure $fd -encoding utf-8
    set doc [dom parse -channel $fd]
    close $fd
    set root [$doc documentElement $doc]
    set text [$root text]
    $doc delete
    string compare $text "\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439"
} {0}
    
test i18n-1.3 {parse utf-8 readFile} {
    set doc [dom parse [::tDOM::xmlReadFile data/i18n_1.xml]]
    set root [$doc documentElement $doc]
    set text [$root text]
    $doc delete
    string compare $text "\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439"
} {0}
    

# cleanup
::tcltest::cleanupTests
return

Added tests/namespace.test.
































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# Features covered:  XML Namespaces
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on XML namespaces.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

proc keysort args {
    array set keyvalue $args
    set result {}
    foreach key [lsort [array names keyvalue]] {
	lappend result $key $keyvalue($key)
    }
    return $result
}

catch {unset result}
catch {unset nsdecls}
proc EStart {tag attlist args} {
    global result nsdecls

    array set extra $args

    catch {eval lappend nsdecls $extra(-namespacedecls)}

    if {[info exists extra(-namespace)]} {
	lappend result $extra(-namespace)^$tag
    } else {
	lappend result $tag
    }
}

proc NSDeclStart {prefix uri} {
    global result

    lappend result $prefix
    lappend result $uri
}

test ns-1.1 {Namespace declaration} {
    set ::result {}
    set ::nsdecls {}

    catch {rename xml::ns-1.1 {}}
    set parser [xml::parser ns-1.1 \
            -namespace \
            -startnamespacedeclcommand NSDeclStart \
            -elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<Test xmlns:test="http://www.zveno.com/Schemas"></Test>
}
    list $::result $::nsdecls
} {{test http://www.zveno.com/Schemas Test} {}}

test ns-1.2 {Multiple namespace declarations} {
    set ::result {}
    set ::nsdecls {}

    catch {rename xml::ns-1.2 {}}
    set parser [xml::parser ns-1.2 \
            -namespace \
            -startnamespacedeclcommand NSDeclStart \
            -elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<Test xmlns:test="http://www.zveno.com/Schemas"
xmlns:x='urn:schema'></Test>
}
    list $::result [eval keysort $::nsdecls]
} {{test http://www.zveno.com/Schemas x urn:schema Test} {}}

test ns-1.3 {Default namespace declaration} {
    set ::result {}
    set ::nsdecls {}

    catch {rename xml::ns-1.3 {}}
    set parser [xml::parser ns-1.3 \
            -namespace \
            -startnamespacedeclcommand NSDeclStart \
            -elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<Test xmlns="http://www.zveno.com/Schemas"
xmlns:x='urn:schema'></Test>
}
    list $::result [eval keysort $::nsdecls]
} {{{} http://www.zveno.com/Schemas x urn:schema http://www.zveno.com/Schemas:Test} {}}

test ns-1.4 {Default namespace declaration w/- separate usage} {
    set ::result {}
    set ::nsdecls {}

    catch {rename xml::ns-1.4 {}}
    set parser [xml::parser ns-1.4 \
            -namespace \
            -startnamespacedeclcommand NSDeclStart \
            -elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<x:Test xmlns="http://www.zveno.com/Schemas"
xmlns:x='urn:schema'><Test/></x:Test>
}
    list $::result [eval keysort $::nsdecls]
} {{{} http://www.zveno.com/Schemas x urn:schema urn:schema:Test http://www.zveno.com/Schemas:Test} {}}

test ns-2.0 {Multiple namespace declarations, same prefix} {
    set ::result {}
    set ::nsdecls {}

    catch {rename xml::ns-2.0 {}}
    set parser [xml::parser ns-2.0 \
            -namespace \
            -startnamespacedeclcommand NSDeclStart \
            -elementstartcommand EStart]
    $parser parse {<?xml version="1.0"?>
<Test>
  <x:Test xmlns:x="http://www.zveno.com/Schemas">
    <x:y/>
  </x:Test>
  <x:Test xmlns:x='urn:schema'>
    <x:z/>
  </x:Test>
</Test>
}
    list $::result [eval keysort $::nsdecls]
} {{Test x http://www.zveno.com/Schemas http://www.zveno.com/Schemas:Test http://www.zveno.com/Schemas:y x urn:schema urn:schema:Test urn:schema:z} {}}

# cleanup
::tcltest::cleanupTests
return
Added tests/parser.test.






























































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# Features covered:  Parser functions
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's basic functions.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1999-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

proc parray arrayName {
    upvar #0 $arrayName arr
    foreach key [lsort [array names $arrayName]] {
	lappend result $key $arr($key)
    }
    return $result
}

catch {unset count} 
proc Count {args} {
    if {![info exists ::count]} {
        set ::count 1
    } else {
        incr ::count
    }
}

catch {unset started}
proc Start {name atList args} {
    array set opts $args
    array set atts $atList

    if {![info exists ::started($name)]} {
	set ::started($name) 1
    } else {
	incr ::started($name)
    }
    if {[info exists atts(class)]} {
	switch $atts(class) {
	    continue {
		return -code continue
	    }
	    break {
		return -code break
	    }
	    error {
		return -code error "error condition in callback"
	    }
	    default {
		return -code $atts(class) 
	    }
	}
    }
}
catch {unset ended}
proc End {name args} {
    array set opts $args
    if {![info exists ::ended($name)]} {
	set ::ended($name) 1
    } else {
	incr ::ended($name)
    }
}
proc PI {name args} {
    return -code $name
}

catch {unset elList}
proc ElStart {name atList args} {
    array set opts {-empty 0}
    array set opts $args
    lappend ::elList start $name $opts(-empty)
}
proc ElEnd {name args} {
    array set opts {-empty 0}
    array set opts $args
    lappend ::elList end $name $opts(-empty)
}

test parser-1.1 {parser creation} {
    set p [::xml::parser]
    regexp {^xmlparser[0-9]+$} $p
} 1

test parser-1.2 {parser creation, only options} {
    set p [::xml::parser -elementstartcommand Start]
    regexp {^xmlparser[0-9]+$} $p
} 1

test parser-1.3 {parser creation, named} {
    catch {rename testparser {}}
    ::xml::parser testparser
} testparser

test parser-1.4 {parser creation, named with options} {
    catch {rename testparser {}}
    ::xml::parser testparser -elementstartcommand Start
} testparser

# Test break return code from callback

test parser-2.1 {break in callback} {
    catch {unset ::started}

    catch {rename parser-2.1 {}}
    set p [::xml::parser parser-2.1 -elementstartcommand Start]
    $p parse {<?xml version="1.0"?>
<Test>
<Element id="el1">Should see this data</Element>
<Element class="break" id="el2">Should not see this data<Element id="el3"/></Element>
<Element id='el4'>Should not see this data</Element>
</Test>
}
    set ::started(Element)
} 2

test parser-2.2 {break in callback} {
    catch {unset ::started}

    catch {rename parser-2.2 {}}
    set p [::xml::parser parser-2.2 -elementstartcommand Start]
    $p parse {<?xml version="1.0"?>
<Test>
<Element>Should see this data</Element>
<Element>Should see this data<Element class="break"/></Element>
<Element>Should not see this data</Element>
</Test>
}
    set ::started(Element)
} 3

test parser-2.3 {break in callback} {
    catch {unset ::started}

    catch {rename parser-2.3 {}}
    set p [::xml::parser parser-2.3 -elementstartcommand Start]
    $p parse {<?xml version="1.0"?>
<Test>
<Element>Should see this data</Element>
<Element>Should see this data
  <?break?>
</Element>
<Element>Should not see this data</Element>
</Test>
}
    set ::started(Element)
} 3

test parser-3.1 {continue in callback} {
    catch {unset ::started}

    catch {rename parser-3.1 {}}
    set p [::xml::parser parser-3.1 -elementstartcommand Start]
    $p parse {<?xml version="1.0"?>
<Test>
<Element id='el1'>Should see this data</Element>
<Element class="continue" id='el2'>Should not see this data
  <Element id='el3'/>
</Element>
<Element id='el4'>Should see this data</Element>
</Test>
}
    set ::started(Element)
} 3

test parser-3.2 {continue in callback} {
    catch {unset ::started}

    catch {rename parser-3.2 {}}
    set p [::xml::parser parser-3.2 -elementstartcommand Start]
    $p parse {<?xml version="1.0"?>
<Test>
<Element>Should see this data</Element>
<Element>Should see this data
  <Element class="continue">
    Should not see this data
    <Element/>
  </Element>
  Should see this data
  <Element/>
</Element>
<Element>Should see this data</Element>
</Test>
}
    set ::started(Element)
} 5

test parser-3.3 {continue in callback} {
    catch {unset ::started}

    catch {rename parser-3.3 {}}
    set p [::xml::parser parser-3.3 -elementstartcommand Start]
    $p parse {<?xml version="1.0"?>
<Test>
<Element>Should see this data</Element>
<Element>Should see this data
  <Element class="continue">
    Should not see this data
    <Element class="break"/>
    break will have no effect
  </Element>
  Should see this data
  <Element/>
</Element>
<Element>Should see this data</Element>
</Test>
}
    set ::started(Element)
} 5

test parser-4.1 {error in callback} {
    catch {unset ::started}

    catch {rename parser-4.1 {}}
    set p [::xml::parser parser-4.1 -elementstartcommand Start]
    set errcode [catch {$p parse {<?xml version="1.0"?>
<Test>
<Element>Should see this data</Element>
<Element class="error"/>
<Element>Should not see this data</Element>
</Test>
}} result]
    list $errcode $::started(Element)
} {1 2}

test parser-4.2 {error in callback} {
    catch {unset ::started}

    catch {rename parser-4.2 {}}
    set p [::xml::parser parser-4.2 -elementstartcommand Start]
    set errcode [catch {$p parse {<?xml version="1.0"?>
<Test>
<Element>Should see this data</Element>
<Element class="13"/>
<Element>Should not see this data</Element>
</Test>
}} result]
    list $::errcode $::started(Element)
} {13 2}

test parser-5.1 {parse channel input} {
    catch {unset ::count}

    catch {rename parser-5.1 {}}
    set parser [::xml::parser parser-5.1 -elementstartcommand Count]
    set fd [open data/books.xml]
    $parser parsechannel $fd
    close $fd
    list $::count
} {42}

# cleanup
::tcltest::cleanupTests
return



Added tests/pcdata.test.


































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# Features covered:  PCDATA
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on PCDATA.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1998-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

catch {unset result}
proc pcdata data {
    append ::result $data
    incr ::pcdataCounter
}
proc Estart {tagName attrList} {
    switch -- $tagName {
	Test {
	}
	default {
	    incr ::element
	}
    }
}

proc EStop tagname {
}

test pcdata-1.1 {Simple PCDATA} {
    set ::result {}
    set ::element 0
    set ::pcdataCounter 0

    catch {rename xml::pcdata-1.1 {}}
    set parser [xml::parser pcdata-1.1 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test>This is PCDATA</Test>
}
    list $::result $::element
} {{This is PCDATA} 0}

test pcdata-1.2 {PCDATA section with Tcl specials} {
    set ::result {}
    set ::element 0
    set ::pcdataCounter 0

    catch {rename xml::pcdata-1.2 {}}
    set parser [xml::parser pcdata-1.2 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test>Dollar $ backslash \ square brackets [ ] braces { }</Test>
}
    list $::result $::element
} {{Dollar $ backslash \ square brackets [ ] braces { }} 0}

# Requested by Marshall Rose, 20/3/1999
test pcdata-1.3 {PCDATA with no entity expansion} {
    set ::result {}
    set ::element 0
    set ::pcdataCounter 0

    catch {rename xml::pcdata-1.3 {}}
    set parser [xml::parser pcdata-1.3 \
	-elementstartcommand Estart \
	-elementendcommand EStop \
	-characterdatacommand pcdata]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test>This is &lt;PCDATA&gt;</Test>
}
    list $::result $::pcdataCounter
} {{This is <PCDATA>} 4}

# cleanup
::tcltest::cleanupTests
return
Added tests/pi.test.
















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# Features covered:  Processing Instructions
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on Processing Instructions.
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1998-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

catch {unset result}
proc PI {target data args} {
    lappend ::result $target $data
}

test pi-1.1 {PI} {
    set ::result {}

    catch {rename xml::pi-1.1 {}}
    set parser [xml::parser pi-1.1 \
	-processinginstructioncommand PI]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><?Test This is a processing instruction?></Test>
}
    set ::result
} {Test {This is a processing instruction}}

test pi-1.2 {PI: missing trailing ?} {
    set ::result {}

    catch {rename xml::pi-1.2 {}}
    set parser [xml::parser pi-1.2 \
	-processinginstructioncommand PI]
    set returncode [catch {$parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><?Test This is a syntax error></Test>
}} msg]

    list $returncode [regexp {error "unclosed token" at.+} $msg]
} {1 1}

test pi-2.1 {PI with special characters} {
    set ::result {}

    catch {rename xml::pi-2.1 {}}
    set parser [xml::parser pi-2.1 \
	-processinginstructioncommand PI]
    $parser parse {<?xml version="1.0"?>
<!DOCTYPE Test>
<Test><?Test [if !VMLRender]?></Test>
}
    set ::result
} {Test {[if !VMLRender]}}

# cleanup
::tcltest::cleanupTests
return
Added tests/xmltest.test.
































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Features covered:  Conformance
#
# This file contains a collection of tests for the TclXML parser.
# This file tests the parser's performance on conformance to the 
# XML specification.  As such it is crude and does not test callback
# features.
#
# Sourcing this file into Tcl runs the tests and generates output
# for errors.  No output means no errors were found.
#
# Copyright (c) 1999-2000 Zveno Pty Ltd.
#
# $Id$

if {[lsearch [namespace children] ::tcltest] == -1} {
    source [file join [pwd] [file dirname [info script]] defs.tcl]
}

if {[lsearch $auto_path [file dirname [file dirname [info script]]]] == -1} {
    set auto_path [linsert $auto_path 0 [file dirname [file dirname [file join [pwd] [info script]]]]]
}

if {[catch {package require expat 2.0}]} {
    catch {puts stderr "Cannot load expat 2.0 package"}
    return
}

proc xmltest {expect dir subdir f} {

    set ch [open $f]
    set data [read $ch]
    close $ch

    test xmltest-$dir-$subdir-[file rootname [file tail $f]] "Document $dir $subdir [file tail $f]" {
	set parser [xml::parser xmltest]
	set code [catch {$parser parse $data}]
	rename $parser {}
	set code
    } $expect
}

# NB. Uses James Clark's test suite for WFF checking.
# Need a framework to test against each file: it's too time-
# consuming to setup a test proc for each one.

set testDir [file join [pwd] xmltest]

# These documents should fail
foreach dir {not-wf} {
    foreach file [glob -nocomplain [file join $testDir $dir sa *.xml]] {
	xmltest 1 $dir sa $file
    }
}

# These documents should pass
foreach dir {invalid valid} {
    foreach file [glob -nocomplain [file join $testDir $dir sa *.xml]] {
	xmltest 0 $dir sa $file
    }
}

# cleanup
::tcltest::cleanupTests
return
Added tests/xpath.test.
























>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12

test xpath-1.1 {function normalize-space} {
    set doc [dom createDocument foo]
    set root [$doc documentElement]
    set r [$root selectNodes {normalize-space('f  ')}]
    $doc delete
    string length $r
} {1}

# cleanup
::tcltest::cleanupTests
return
Added tests/xslt.test.






















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59


test xslt-1.1 {unicode chars outside of US-ASCII in var name} {
     set xml [dom parse {<root/>}]
     set xslt [dom parse [tDOM::xmlReadFile data/xslt_1.xsl]]
     set xmlroot [$xml documentElement]
     $xmlroot xslt $xslt resultDoc
     set resultroot [$resultDoc documentElement]
     set result [$resultroot asXML]
     $xml delete
     $xslt delete
     $resultDoc delete
     set result
} {foo}


test xslt-1.2 {xpath parse real number} {
     set xml [dom parse {<root/>}]
     set xslt [dom parse {<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">
  <xsl:template match="/">
      <xsl:value-of select=".12345"/>
  </xsl:template>
</xsl:stylesheet>}]
     set xmlroot [$xml documentElement]
     $xmlroot xslt $xslt resultDoc
     set resultroot [$resultDoc documentElement]
     set result [$resultroot asXML]
     $xml delete
     $xslt delete
     $resultDoc delete
     set result
} {0.12345}

test xslt-1.2 {xpath parse real number} {
     set xml [dom parse {<root/>}]
     set xslt [dom parse {<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">
  <xsl:template match="/">
      <xsl:value-of select="-.12345"/>
  </xsl:template>
</xsl:stylesheet>}]
     set xmlroot [$xml documentElement]
     $xmlroot xslt $xslt resultDoc
     set resultroot [$resultDoc documentElement]
     set result [$resultroot asXML]
     $xml delete
     $xslt delete
     $resultDoc delete
     set result
} {-0.12345}
     


# cleanup
::tcltest::cleanupTests
return
Changes to unix/configure.
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# Set your version numbers here.  The NODOT_VERSION is required
# for constructing the library name on systems that don't like dots
# in library names (Windows).  The VERSION variable is used on the
# other systems.
#--------------------------------------------------------------------

MAJOR_VERSION=0
MINOR_VERSION=6
PATCHLEVEL=0
VERSION=${MAJOR_VERSION}.${MINOR_VERSION}

PACKAGE=tdom










|







538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
# Set your version numbers here.  The NODOT_VERSION is required
# for constructing the library name on systems that don't like dots
# in library names (Windows).  The VERSION variable is used on the
# other systems.
#--------------------------------------------------------------------

MAJOR_VERSION=0
MINOR_VERSION=7
PATCHLEVEL=0
VERSION=${MAJOR_VERSION}.${MINOR_VERSION}

PACKAGE=tdom



Added win/config.h.
Added win/makefile.vc.


































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#----------------------------------------------------------------------------
#   This is derivated from the tcl8.3 win makefile and surely not
#   perfect. It works for me. 
#   rolf ade, 2001 ([email protected])
#   
#
#
#   Project directories
#
#   ROOT   = top of source tree
#
#   TOOLS32 = location of VC++ 32-bit development tools.
#
#   INSTALLDIR = location of the Tcl installation
#
#----------------------------------------------------------------------------

!if "$(MSVCDIR)" == ""
MSG = ^
You'll need to run vcvars32.bat from Developer Studio, first, to setup^
the environment.
!error $(MSG)
!endif


# Set this to the appropriate value of /MACHINE: for your platform
MACHINE                = IX86
ROOT           = ..
INSTALLDIR     = c:\Progra~1\Tcl

TOOLS32        = $(MSVCDIR)
TOOLS32_rc     = $(MSVCDIR)\..\common\MSDev98

# Uncomment the following line to compile with thread support
#THREADDEFINES = -DTCL_THREADS=1

# Set NODEBUG to 0 to compile with symbols
NODEBUG = 1

# The following defines can be used to control the amount of debugging
# code that is added to the compilation.
#
#      -DTCL_MEM_DEBUG         Enables the debugging memory allocator.
#      -DTCL_COMPILE_DEBUG     Enables byte compilation logging.
#      -DTCL_COMPILE_STATS     Enables byte compilation statistics gathering.
#      -DUSE_TCLALLOC=0        Disables the Tcl memory allocator in favor
#                              of the native malloc implementation.  This is
#
# DEBUGDEFINES = -DTCL_MEM_DEBUG -DTCL_COMPILE_DEBUG -DTCL_COMPILE_STATS
# DEBUGDEFINES = -DUSE_TCLALLOC=0


#-------------------------------------------------------------------------
#
#   Do not modify below this line
#
#-------------------------------------------------------------------------

NAMEPREFIX = tdom
STUBPREFIX = $(NAMEPREFIX)stub
DOTVERSION = 0.7
VERSION = 07

BINROOT         = .
!IF "$(NODEBUG)" == "1"
TMPDIRNAME      =
DBGX            =
!ELSE
TMPDIRNAME      = Debug
DBGX            = d
!ENDIF
TMPDIR          = $(BINROOT)
OUTDIRNAME      = $(TMPDIRNAME)
OUTDIR          = $(TMPDIR)
TOP_DIR         = $(BINROOT)\..

TDOMLIB         = $(OUTDIR)\$(NAMEPREFIX)$(VERSION)$(DBGX).lib
TDOMDLLNAME     = $(NAMEPREFIX)$(VERSION)$(DBGX).dll
TDOMDLL         = $(OUTDIR)\$(TDOMDLLNAME)

MKDIR           = .\mkd.bat
RM              = del

LIB_INSTALL_DIR        = $(INSTALLDIR)\lib
BIN_INSTALL_DIR        = $(INSTALLDIR)\bin
SCRIPT_INSTALL_DIR     = $(INSTALLDIR)\lib\tcl$(DOTVERSION)
INCLUDE_INSTALL_DIR    = $(INSTALLDIR)\include


TDOMOBJS = $(TMPDIR)\xmlrole.obj    \
           $(TMPDIR)\xmltok.obj     \
           $(TMPDIR)\xmlparse.obj   \
           $(TMPDIR)\xmlsimple.obj  \
           $(TMPDIR)\utf8conv.obj   \
           $(TMPDIR)\dom.obj        \
           $(TMPDIR)\domalloc.obj   \
	   $(TMPDIR)\domhtml.obj    \
	   $(TMPDIR)\domxslt.obj    \
	   $(TMPDIR)\nodecmd.obj    \
           $(TMPDIR)\domxpath.obj   \
           $(TMPDIR)\tclexpat.obj   \
           $(TMPDIR)\tcldom.obj     \
           $(TMPDIR)\tdominit.obj

cc32           = "$(TOOLS32)\bin\cl.exe"
link32         = "$(TOOLS32)\bin\link.exe"
rc32           = "$(TOOLS32_rc)\bin\rc.exe"
include32      = -I"$(TOOLS32)\include"
libpath32      = /LIBPATH:"$(TOOLS32)\lib"
tcllibpath     = /LIBPATH:"$(INSTALLDIR)\lib"
lib32          = "$(TOOLS32)\bin\lib.exe"

WINDIR         = $(ROOT)\win
GENERICDIR     = $(ROOT)\generic
EXPATDIR       = $(ROOT)\expat-1.95.1
TCLINCDIR      = $(INSTALLDIR)\Include

TCL_INCLUDES   = -I"$(WINDIR)" -I"$(GENERICDIR)" -I"$(EXPATDIR)" -I"$(TCLINCDIR)"
TCL_DEFINES    = $(DEBUGDEFINES) $(THREADDEFINES)

#-------------------------------------------------------------------------
#
#   Compile flags
#
#-------------------------------------------------------------------------

!IF "$(NODEBUG)" == "1"
# This cranks the optimization level to maximize speed
cdebug = -O2 -Gs -GD
!ELSE
!IF "$(MACHINE)" == "IA64"
cdebug = -Od -Zi
!ELSE
cdebug = -Z7 -Od
!ENDIF
!ENDIF

# declarations common to all compiler options
cflags = -c -W3 -nologo -Fp$(TMPDIR)\ -YX -DXML_DTD -DXML_NS -DUSE_TCL_STUBS -DCOMPILED_FROM_DSP -DVERSION="\"1.95.1\""
#cflags = -c -W3 -nologo -Fp$(TMPDIR)\ -YX -DXML_DTD -DXML_NS -DCOMPILED_FROM_DSP -DVERSION="\"1.95.1\""
cvarsdll = -MD$(DBGX)

TCL_CFLAGS     = $(cdebug) $(cflags) $(cvarsdll) $(include32) \
                       $(TCL_INCLUDES) $(TCL_DEFINES)
CON_CFLAGS     = $(cdebug) $(cflags) $(include32) -DCONSOLE

#-------------------------------------------------------------------------
#
#   Link flags
#
#-------------------------------------------------------------------------

!IF "$(NODEBUG)" == "1"
ldebug = /RELEASE
!ELSE
ldebug = -debug:full -debugtype:cv
!ENDIF

# declarations common to all linker options
lflags = /NODEFAULTLIB /NOLOGO /MACHINE:$(MACHINE) $(libpath32) $(tcllibpath)

# declarations for use on Intel i386, i486, and Pentium systems
DLLENTRY = @12
dlllflags = $(lflags) -entry:_DllMainCRTStartup$(DLLENTRY) -dll


conlflags = $(lflags) -subsystem:console -entry:mainCRTStartup
guilflags = $(lflags) -subsystem:windows -entry:WinMainCRTStartup

libc = libc$(DBGX).lib oldnames.lib
libcdll = msvcrt$(DBGX).lib oldnames.lib

baselibs   = kernel32.lib $(optlibs) advapi32.lib user32.lib tclstub83$(DBGX).lib
#baselibs    = kernel32.lib $(optlibs) advapi32.lib user32.lib tcl83.lib
winlibs     = $(baselibs) gdi32.lib comdlg32.lib winspool.lib


guilibs     = $(libc) $(winlibs)
conlibs     = $(libc) $(baselibs)
guilibsdll  = $(libcdll) $(winlibs)
conlibsdll  = $(libcdll) $(baselibs)

#-------------------------------------------------------------------------
#
#   Project specific targets
#
#-------------------------------------------------------------------------

dlls:      $(TDOMDLL)
all:       dlls

install:   all
	@echo installing tDOM
	@$(MKDIR) "$(INSTALLDIR)\lib\tDOM"
	@xcopy /y $(TDOMDLL) "$(INSTALLDIR)\lib\tDOM"
	@xcopy /y pkgIndex.tcl "$(INSTALLDIR)\lib\tDOM"
	@xcopy /y ..\lib\tdom.tcl "$(INSTALLDIR)\lib\tDOM"
	@xcopy /y ..\lib\domhtml.tcl "$(INSTALLDIR)\lib\tDOM"

$(TDOMLIB): $(TDOMDLL)

$(TDOMDLL): $(TDOMOBJS)
       $(link32) $(ldebug) $(dlllflags) \
               -out:$@ $(guilibsdll) @<<
$(TDOMOBJS)
<<

#-------------------------------------------------------------------------
#   Implicit rules
#-------------------------------------------------------------------------

{$(EXPATDIR)}.c{$(TMPDIR)}.obj:
    $(cc32) -DBUILD_tcl $(TCL_CFLAGS) -Fo$(TMPDIR)\ $<

{$(GENERICDIR)}.c{$(TMPDIR)}.obj:
    $(cc32) -DBUILD_tcl $(TCL_CFLAGS) -Fo$(TMPDIR)\ $<

clean:
       -@$(RM) $(OUTDIR)\*.exp 2>nul
       -@$(RM) $(OUTDIR)\*.lib 2>nul
       -@$(RM) $(OUTDIR)\*.dll 2>nul
       -@$(RM) $(TMPDIR)\*.pch 2>nul
       -@$(RM) $(TMPDIR)\*.obj 2>nul
       -@$(RM) $(TMPDIR)\*.ilk 2>nul
       -@$(RM) $(TMPDIR)\*.pdb 2>nul
Added win/mkd.bat.


























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
@echo off
rem RCS: @(#) $Id$

if exist %1\nul goto end

md %1
if errorlevel 1 goto end

echo Created directory %1

:end


Added win/pkgIndex.tcl.










>
>
>
>
>
1
2
3
4
5
# tDOM Tcl package index file

package ifneeded tdom 0.7        \
    "source [file join $dir tdom.tcl]; \
     load   [file join $dir tdom07[info sharedlibextension] ] tdom  "