File: xmlsimple.c

package info (click to toggle)
tdom 0.9.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 7,260 kB
  • sloc: ansic: 56,762; xml: 20,797; tcl: 3,618; sh: 658; makefile: 83; cpp: 30
file content (1095 lines) | stat: -rw-r--r-- 44,383 bytes parent folder | download
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
/*----------------------------------------------------------------------------
|   Copyright (c) 1999  Jochen Loewer (loewerj@hotmail.com)
|-----------------------------------------------------------------------------
|
|
|   A simple (hopefully fast) parser to build up a DOM structure in memory.
|   Initially based on Richard Hipp's XML parser for TMML.
|
|
|   The contents of this file are subject to the Mozilla Public License
|   Version 2.0 (the "License"); you may not use this file except in
|   compliance with the License. You may obtain a copy of the License at
|   http://www.mozilla.org/MPL/
|
|   Software distributed under the License is distributed on an "AS IS"
|   basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
|   License for the specific language governing rights and limitations
|   under the License.
|
|   The Original Code is tDOM.
|
|   The Initial Developer of the Original Code is Jochen Loewer
|   Portions created by Jochen Loewer are Copyright (C) 1998, 1999
|   Jochen Loewer. All Rights Reserved.
|
|   Contributor(s):
|
|       June00  Zoran Vasiljevic  Made thread-safe.
|
|
|   adopted/written by Jochen Loewer
|   July 1999
|
|   ------------------------------------------------------------------------
|
|   Partly based on a parser for XML (for TMML by R.Hipp 1998). 
|   This source code is released into the public domain by the author.
|   on 2002, December 17.
|
\---------------------------------------------------------------------------*/


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

/*----------------------------------------------------------------------------
|   Defines
|
\---------------------------------------------------------------------------*/
#define DBG(x)          
#define TDOM_NS
#ifdef TDOM_NS
# define RetError(m,p) *errStr=m; *pos=p; FREE((char*)activeNS); return TCL_ERROR;
#else 
# define RetError(m,p) *errStr=m; *pos=p; return TCL_ERROR;
#endif
#define SPACE(c)       ((c)==' ' || (c)=='\n' || (c)=='\t' || (c)=='\r')

/*----------------------------------------------------------------------------
|   Begin Character Entity Translator
|
|
|   The next section of code implements routines used to translate
|   character entity references into their corresponding strings.
|
|   Examples:
|
|         &amp;          "&"
|         &lt;           "<"
|         &gt;           ">"
|         &nbsp;         " "
|
\---------------------------------------------------------------------------*/


/*----------------------------------------------------------------------------
|   Each entity reference is recorded as an instance of the following
|   structure
\---------------------------------------------------------------------------*/
typedef struct Er Er;
struct Er {
    char *zName;     /* The name of this entity reference.  ex:  "amp" */
    char *zValue;    /* The value for this entity.          ex:  "&"   */
    Er *pNext;       /* Next entity with the same hash on zName        */
};


/*----------------------------------------------------------------------------
|   The size of the hash table.  For best results this should
|   be a prime number which is about the same size as the number of
|   character entity references known to the system.
|
\---------------------------------------------------------------------------*/
#define ER_HASH_SIZE 7


/*----------------------------------------------------------------------------
|   The following flag is TRUE if entity reference hash table needs
|   to be initialized.
|
|   Hash table is used read-only, therefore, just one copy, protected with
|   mutex when used in threading environments. The mutex is used only for
|   initial setup of the table.
|
\---------------------------------------------------------------------------*/
static int bErNeedsInit = 1;
TDomThreaded(static Tcl_Mutex initMutex;)


/*----------------------------------------------------------------------------
|   The hash table
|
|   If the name of an entity reference hashes to the value H, then
|   apErHash[H] will point to a linked list of Er structures, one of
|   which will be the Er structure for that entity reference
|
\---------------------------------------------------------------------------*/
static Er *apErHash[ER_HASH_SIZE];


/*----------------------------------------------------------------------------
|   ErHash  --
|
|       Hash an entity reference name.  The value returned is an
|       integer between 0 and Er_HASH_SIZE-1, inclusive.
|
\---------------------------------------------------------------------------*/
static int ErHash(
    const char *zName
)
{
    int h = 0;      /* The hash value to be returned */
    char c;         /* The next character in the name being hashed */

    while( (c=*zName)!=0 ){
        h = h<<5 ^ h ^ c;
        zName++;
    }
    if( h<0 ) h = -h;
    return h % ER_HASH_SIZE;

} /* ErHash */


/*----------------------------------------------------------------------------
|   The following is a table of all entity references.  To create
|   new character entities, add entries to this table.
|
|   Note: For the decoder to work, the name of the entity reference
|   must not be shorter than the value.
|
\---------------------------------------------------------------------------*/
static Er er_sequences[] = {
    { "amp",       "&",        0 },
    { "lt",        "<",        0 },
    { "gt",        ">",        0 },
    { "apos",      "'",        0 },
    { "quot",      "\"",       0 },
    { "nbsp",      "\xC2\xA0",    0 },
};


/*----------------------------------------------------------------------------
|   ErInit --
|
|       Initialize the entity reference hash table
|
\---------------------------------------------------------------------------*/
static void ErInit (void)
{
    size_t i;  /* For looping through the list of entity references */
    int h;  /* The hash on a entity */

    for(i=0; i<sizeof(er_sequences)/sizeof(er_sequences[0]); i++){
        h = ErHash(er_sequences[i].zName);
        er_sequences[i].pNext = apErHash[h];
        apErHash[h] = &er_sequences[i];
    }

} /* ErInit */


/*----------------------------------------------------------------------------
|    TranslateEntityRefs  --
|
|        Translate entity references and character references in the string
|        "z".  "z" is overwritten with the translated sequence.
|
|        Unrecognized entity references are unaltered.
|
|        Example:
|
|          input =    "AT&amp;T &gt MCI"
|          output =   "AT&T > MCI"
|
\---------------------------------------------------------------------------*/
static int TranslateEntityRefs (
    char *z,
    int  *newLen
)
{
    int from;    /* Read characters from this position in z[] */
    int to;      /* Write characters into this position in z[] */
    int h;       /* A hash on the entity reference */
    char *zVal;  /* The substituted value */
    Er *p;       /* For looping down the entity reference collision chain */
    int value;

    from = to = 0;

    /*---------------------------------------------
     |   This is done only once per process
     \--------------------------------------------*/

    if (bErNeedsInit) {
        TDomThreaded(Tcl_MutexLock(&initMutex);)
        if (bErNeedsInit) {
            ErInit();
            bErNeedsInit = 0;
        }
        TDomThreaded(Tcl_MutexUnlock(&initMutex);)
    }

    while (z[from]) {
        if (z[from]=='&') {
            int i = from+1;
            int c;

            if (z[i] == '#') {
                /*---------------------------------------------
                |   convert character reference
                \--------------------------------------------*/
                value = 0;
                if (z[++i] == 'x') {
                    i++;
                    while (z[i] && (c=z[i]) && (c!=';')) {
                        value = value * 16;
                        if ((c>='0') && (c<='9')) {
                            value += c-'0';
                        } else
                        if ((c>='A') && (c<='F')) {
                            value += c-'A' + 10;
                        } else
                        if ((c>='a') && (c<='f')) {
                            value += c-'a' + 10;
                        } else {
                            /* error */
                            return 0;
                        }
                        i++;
                    }
                } else {
                    while (z[i] && (c=z[i]) && (c!=';')) {
                        value = value * 10;
                        if ((c>='0') && (c<='9')) {
                            value += c-'0';
                        } else {
                            /* error */
                            return 0;
                        }
                        i++;
                    }
                }
                if (!z[i] || (z[i]!=';')) {
                    return 0;
                    /* error */
                }
                from = i+1;
                if (value < 0x80) {
                    z[to++] = value;
                } else if (value <= 0x7FF) {
                    z[to++] = (char) ((value >> 6) | 0xC0);
                    z[to++] = (char) ((value | 0x80) & 0xBF);
                } else if (value <= 0xFFFF) {
                    z[to++] = (char) ((value >> 12) | 0xE0);
                    z[to++] = (char) (((value >> 6) | 0x80) & 0xBF);
                    z[to++] = (char) ((value | 0x80) & 0xBF);
                } else {
                    /* error */
                    return 0;
                }
            } else {
                while (z[i] && isalpha((unsigned char)z[i])) {
                   i++;
                }
                if (!z[i] || (z[i]!=';')) {
                    return 0;
                }
                c = z[i];
                z[i] = 0;
                h = ErHash(&z[from+1]);
                p = apErHash[h];
                while (p && strcmp(p->zName,&z[from+1])!=0 ) {
                    p = p->pNext;
                }
                z[i] = c;
                if (p) {
                    zVal = p->zValue;
                    while (*zVal) {
                        z[to++] = *(zVal++);
                    }
                    from = i;
                    if (c==';') from++;
                } else {
                    z[to++] = z[from++];
                }
            }
        } else {
            z[to++] = z[from++];
        }
    }
    z[to] = 0;
    *newLen = to;
    return 1;
}
/*----------------------------------------------------------------------------
|   End Of Character Entity Translator
\---------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
|   XML_SimpleParse (non recursive)
|
|       Parses the XML string starting at 'pos' and continuing to the
|       first encountered error.
|
\---------------------------------------------------------------------------*/
static int
XML_SimpleParse (
    char        *xml,   /* XML string  */
    int         *pos,   /* Index of next unparsed character in xml */
    domDocument *doc,
    domNode     *parent,
    int          ignoreWhiteSpaces,
    int          keepCDATA,
    int          forest,
    char       **errStr
) {
    register int   c;          /* Next character of the input file */
    register char *pn;
    register char *x, *start, *piSep;
    int            saved;
    int            hasContent;
    domNode       *node;
    domNode       *parent_node = parent;
    domTextNode   *tnode;
    domAttrNode   *attrnode, *lastAttr, *attrList;
    int            ampersandSeen = 0;
    int            only_whites   = 0;
    domProcessingInstructionNode *pinode;
    int            hnew;
    Tcl_HashEntry *h;

#ifdef TDOM_NS    
    int            nspos, newNS;
    int            depth = 0;
    int            activeNSpos  = -1;
    int            activeNSsize = 8;
    domActiveNS   *activeNS     = (domActiveNS*) MALLOC (sizeof(domActiveNS) * activeNSsize);
    const char    *xmlns, *localname;
    domNS         *ns;
    char           tagPrefix[MAX_PREFIX_LEN];
    char           prefix[MAX_PREFIX_LEN];
    domAttrNode   *lastNSAttr, *NSattrList;
#endif

    x = &(xml[*pos]);

    while ( (c=*x)!=0 ) {

        start = x;

        if (c!='<') {
            /*----------------------------------------------------------------
            |   read text between tags
            |
            \---------------------------------------------------------------*/
            ampersandSeen = 0;
            only_whites = 1;
            while ( (c=*x)!=0 && c!='<' ) {
                if (c=='&') ampersandSeen = 1;
                if ( (c != ' ')  &&
                     (c != '\t') &&
                     (c != '\n') &&
                     (c != '\r') ) {
                    only_whites = 0;
                }
                x++;
            }
            if (!(only_whites && ignoreWhiteSpaces) && parent_node) {
                if (parent_node->lastChild
                    && parent_node->lastChild->nodeType == TEXT_NODE) {
                    /* normalize text node, i.e. there are no adjacent
                     * text nodes */
                    tnode = (domTextNode*)parent_node->lastChild;
                    tnode->nodeValue = REALLOC(tnode->nodeValue,
                                               tnode->valueLength + x - start + 1);
                    memmove(tnode->nodeValue + tnode->valueLength,
                            start, x - start);
                    saved = tnode->valueLength;
                    tnode->valueLength += (x - start);
                    *(tnode->nodeValue + tnode->valueLength) = 0;
                    if (ampersandSeen) {
                        if (!TranslateEntityRefs(tnode->nodeValue + saved, 
                                                 &(tnode->valueLength) )) {
                            RetError("Entity parsing error", (x - xml));
                        }
                        tnode->valueLength += saved;
                    }
                } else {
                    /*--------------------------------------------------------
                      |   allocate new TEXT node
                      \-------------------------------------------------------*/
                    tnode = (domTextNode*) domAlloc(sizeof(domTextNode));
                    memset(tnode, 0, sizeof(domTextNode));
                    tnode->nodeType    = TEXT_NODE;
                    tnode->ownerDocument = doc;
                    tnode->nodeNumber  = NODE_NO(doc);
                    tnode->valueLength = (x - start);
                    tnode->nodeValue   = (char*)MALLOC((x - start)+1);
                    memmove(tnode->nodeValue, start, (x - start));
                    *(tnode->nodeValue + (x - start)) = 0;
                    tnode->parentNode = parent_node;
                    if (parent_node->firstChild)  {
                        parent_node->lastChild->nextSibling = (domNode*)tnode;
                        tnode->previousSibling = parent_node->lastChild;
                        parent_node->lastChild = (domNode*)tnode;
                    } else {
                        parent_node->firstChild = parent_node->lastChild = 
                            (domNode*)tnode;
                    }
                    if (ampersandSeen) {
                        if (!TranslateEntityRefs(tnode->nodeValue, 
                                                 &(tnode->valueLength) )) {
                            RetError("Entity parsing error", (x - xml));
                        }
                    }
                }
            }

        } else if (x[1]=='/') {
            /*------------------------------------------------------------
            |   read and check closing tag
            \-----------------------------------------------------------*/
            node = parent_node;
            if (!parent_node) {
                RetError("Syntax error",(x - xml));
            }
            parent_node = node->parentNode;
            pn = (char*)node->nodeName;

            x += 2;
            while (*x == *pn) { x++; pn++; }
            if ( *pn || (*x!='>' && !SPACE(*x) ) ) {
                RetError("Unterminated element",(x - xml));
            }
            while (SPACE(*x)) {
                x++;
            }
            if (*x=='>') {
                x++;
            } else {
                RetError("Missing \">\"",(x - xml)-1);
            }
#ifdef TDOM_NS 
            depth--;
            /* pop active namespaces */
            while ( (activeNSpos >= 0) &&
                    (activeNS[activeNSpos].depth == depth) )
            {
                activeNSpos--;
            } 
#endif                                   
            if (parent_node == NULL) {
                /* we return to main node and so finished parsing */
#ifdef TDOM_NS
                FREE ((char *) activeNS);
#endif                
                return TCL_OK;
            }
            continue;

        } else {

            x++;
            if (*x=='!') {
                if (x[1]=='-' && x[2]=='-') {
                    /*--------------------------------------------------------
                    |   read over a comment
                    \-------------------------------------------------------*/
                    x += 3;
                    while ( (c=*x)!=0 &&
                            (c!='-' || x[1]!='-' || x[2]!='>')) {
                        x++;
                    }
                    if (*x) {
                        /*----------------------------------------------------
                        |   allocate new COMMENT node for comments
                        \---------------------------------------------------*/
                        tnode = (domTextNode*) domAlloc(sizeof(domTextNode));
                        memset(tnode, 0, sizeof(domTextNode));
                        tnode->nodeType      = COMMENT_NODE;
                        tnode->ownerDocument = doc;
                        tnode->nodeNumber    = NODE_NO(doc);
                        tnode->parentNode    = parent_node;
                        tnode->valueLength   = x - start - 4;
                        tnode->nodeValue     = (char*)MALLOC(tnode->valueLength+1);
                        memmove(tnode->nodeValue, start+4, tnode->valueLength);
                        *(tnode->nodeValue + tnode->valueLength) = 0;
                        if (parent_node == NULL) {
                            if (doc->rootNode->lastChild) {
                                tnode->previousSibling = 
                                    doc->rootNode->lastChild;
                                doc->rootNode->lastChild->nextSibling 
                                    = (domNode*)tnode;
                            } else {
                                doc->rootNode->firstChild = (domNode*) tnode;
                            }
                            doc->rootNode->lastChild = (domNode*) tnode;
                        } else {
                            if (parent_node->firstChild)  {
                                parent_node->lastChild->nextSibling = (domNode*)tnode;
                                tnode->previousSibling = parent_node->lastChild;
                                parent_node->lastChild = (domNode*)tnode;
                            } else {
                                parent_node->firstChild = parent_node->lastChild = (domNode*)tnode;
                            }
                        }
                        x += 3;
                    } else {
                        RetError("Unterminated comment",(start-xml));
                    }
                    continue;

                } else if (x[1]=='D' && x[2]=='O' &&
                           x[3]=='C' && x[4]=='T' &&
                           x[5]=='Y' && x[6]=='P' && x[7]=='E' ) {
                    /*--------------------------------------------------------
                    |   read over a DOCTYPE definition
                    \-------------------------------------------------------*/
                    x += 8;
                    start = x;
                    while (*x!=0) {
                        if (*x=='[') {
                            x++;
                            while ((*x!=0) && (*x!=']')) x++;
                        } else
                        if (*x=='>') {
                            break;
                        } else {
                            x++;
                        }
                    }
                    if (*x) {
                        x++;
                    } else {
                        RetError("Unterminated DOCTYPE definition",(start-xml));
                    }
                    continue;

                } else if (x[1]=='[' && x[2]=='C' &&
                           x[3]=='D' && x[4]=='A' &&
                           x[5]=='T' && x[6]=='A' && x[7]=='[' ) {
                    /*--------------------------------------------------------
                    |   read over a <![CDATA[ section
                    \-------------------------------------------------------*/
                    x += 8;
                    start = x;
                    only_whites = 1;
                    while ( ((c=*x)!=0) &&
                            ((*x!=']') || (x[1]!=']') || (x[2]!='>'))) {
                        if (only_whites &&
                            (c != ' ')  &&
                            (c != '\t') &&
                            (c != '\n') &&
                            (c != '\r') ) {
                            only_whites = 0;
                        }
                        x++;
                    }
                    if (*x) {
                        if (parent_node && ((x - start) || keepCDATA)) {
                            if (parent_node->lastChild
                                && parent_node->lastChild->nodeType == TEXT_NODE
                                && !keepCDATA) {
                                if ((x - start) && !(only_whites && ignoreWhiteSpaces)) {
                                    /* normalize text node, i.e. there
                                     * are no adjacent text nodes */
                                    tnode = (domTextNode*)parent_node->lastChild;
                                    tnode->nodeValue =
                                        REALLOC(tnode->nodeValue,
                                                tnode->valueLength + x - start + 1);
                                    memmove(tnode->nodeValue + tnode->valueLength,
                                            start, x - start);
                                    tnode->valueLength += (x - start);
                                    *(tnode->nodeValue + tnode->valueLength) = 0;
                                }
                            } else {
                                if (!(only_whites && ignoreWhiteSpaces)
                                    && ((x - start) || keepCDATA)) {
                                    /*----------------------------------------------------
                                      |   allocate new node for CDATA section data
                                      \---------------------------------------------------*/
                                    tnode = (domTextNode*) domAlloc(sizeof(domTextNode));
                                    memset(tnode, 0, sizeof(domTextNode));
                                    if (keepCDATA)
                                        tnode->nodeType      = CDATA_SECTION_NODE;
                                    else 
                                        tnode->nodeType      = TEXT_NODE;
                                    tnode->ownerDocument = doc;
                                    tnode->nodeNumber    = NODE_NO(doc);
                                    tnode->parentNode    = parent_node;
                                    tnode->valueLength   = (x - start);
                                    tnode->nodeValue     = (char*)MALLOC((x - start)+1);
                                    memmove(tnode->nodeValue, start, (x - start));
                                    *(tnode->nodeValue + (x - start)) = 0;
                                    if (parent_node->firstChild)  {
                                        parent_node->lastChild->nextSibling = (domNode*)tnode;
                                        tnode->previousSibling = parent_node->lastChild;
                                        parent_node->lastChild = (domNode*)tnode;
                                    } else {
                                        parent_node->firstChild = parent_node->lastChild = (domNode*)tnode;
                                    }
                                }
                            }
                        }
                        x += 3;
                    } else {
                        RetError("Unterminated CDATA definition",(start-xml) );
                    }
                    continue;
                 } else {
                        RetError("Incorrect <!... tag",(start-xml) );
                 }

            } else if (*x=='?') {
                /*--------------------------------------------------------
                |   read over a processing instructions(PI) / XMLDecl
                \-------------------------------------------------------*/
                x++;
                start = x;
                while ( (c=*x)!=0 &&
                        (c!='?' || x[1]!='>')) {
                    x++;
                }
                if (*x) {
                    /*------------------------------------------------------------
                    |   allocate new PI node for processing instruction section
                    \-----------------------------------------------------------*/
                    pinode = (domProcessingInstructionNode*)
                            domAlloc(sizeof(domProcessingInstructionNode));
                    memset(pinode, 0, sizeof(domProcessingInstructionNode));
                    pinode->nodeType      = PROCESSING_INSTRUCTION_NODE;
                    pinode->ownerDocument = doc;
                    pinode->nodeNumber    = NODE_NO(doc);
                    pinode->parentNode    = parent_node;

                    /*-------------------------------------------------
                    |   extract PI target
                    \------------------------------------------------*/
                    piSep = start;
                    while ( (c=*piSep)!=0 && !SPACE(c) &&
                            (c!='?' || piSep[1]!='>')) {
                         piSep++;
                    }
                    *piSep = '\0'; /* temporarily terminate the string */

                    pinode->targetLength = strlen(start);
                    pinode->targetValue  = (char*)MALLOC(pinode->targetLength);
                    memmove(pinode->targetValue, start, pinode->targetLength);

                    *piSep = c;  /* remove temporarily termination */

                    /*-------------------------------------------------
                    |   extract PI data
                    \------------------------------------------------*/
                    while (SPACE(*piSep)) {
                        piSep++;
                    }
                    pinode->dataLength = x - piSep;
                    pinode->dataValue  = (char*)MALLOC(pinode->dataLength);
                    memmove(pinode->dataValue, piSep, pinode->dataLength);

                    if (parent_node == NULL) {
                        if (doc->rootNode->lastChild) {
                            pinode->previousSibling = doc->rootNode->lastChild;
                            doc->rootNode->lastChild->nextSibling 
                                = (domNode*) pinode;
                        } else {
                            doc->rootNode->firstChild = (domNode*) pinode;
                        }
                        doc->rootNode->lastChild = (domNode*) pinode;
                    } else {
                        if (parent_node->firstChild)  {
                            parent_node->lastChild->nextSibling = (domNode*)pinode;
                            pinode->previousSibling = parent_node->lastChild;
                            parent_node->lastChild = (domNode*)pinode;
                        } else {
                            parent_node->firstChild = parent_node->lastChild = (domNode*)pinode;
                        }
                    }
                    x += 2;
                } else {
                    RetError("Unterminated processing instruction(PI)",(start-xml) );
                }
                continue;
            }

            /*----------------------------------------------------------------
            |   new tag/element
            |
            \---------------------------------------------------------------*/
            hasContent = 1;
            while ((c=*x)!=0 && c!='/' && c!='>' && !SPACE(c) ) {
                x++;
            }
            if (c==0) {
                RetError("Missing \">\"",(start-xml) );
            }
            if ( (x-start)==1) {
                RetError("Null markup name",(start-xml) );
            }
            *x = '\0'; /* temporarily terminate the string */

            /*------------------------------------------------------
            |   create new DOM element node
            \-----------------------------------------------------*/
            h = Tcl_CreateHashEntry(&HASHTAB(doc,tdom_tagNames), start+1,
                                    &hnew);
            node = (domNode*) domAlloc(sizeof(domNode));
            memset(node, 0, sizeof(domNode));
            node->nodeType      = ELEMENT_NODE;
            node->nodeName      = (char *)&(h->key);
            node->ownerDocument = doc;
            node->nodeNumber    = NODE_NO(doc);
            node->ownerDocument = doc;

            if (parent_node == NULL) {
                if (doc->rootNode->lastChild) {
                    node->previousSibling = doc->rootNode->lastChild;
                    doc->rootNode->lastChild->nextSibling = node;
                } else {
                    doc->rootNode->firstChild = node;
                }
                doc->rootNode->lastChild = node;
            } else {
                node->parentNode = parent_node;
                if (parent_node->firstChild)  {
                    parent_node->lastChild->nextSibling = node;
                    node->previousSibling = parent_node->lastChild;
                    parent_node->lastChild = node;
                } else {
                    parent_node->firstChild = parent_node->lastChild = node;
                }
            }

            *x = c;  /* remove temporarily termination */

            while (SPACE(*x) ) {
                x++;
            }
            /*-----------------------------------------------------------
            |   read attribute name-value pairs
            \----------------------------------------------------------*/
            lastAttr = NULL;
            attrList = NULL;
#ifdef TDOM_NS
            lastNSAttr = NULL;
            NSattrList = NULL;
#endif            
            while ( (c=*x) && (c!='/') && (c!='>') ) {
                char *ArgName = x;
                int nArgName;
                char *ArgVal = NULL;
                int nArgVal = 0;

                while ((c=*x)!=0 && c!='=' && c!='>' && !SPACE(c) ) {
                    x++;
                }
                nArgName = x - ArgName;
                while (SPACE(*x)) {
                    x++;
                }
                if (*x=='=') {
                    x++;
                }
                saved = *(ArgName + nArgName);
                *(ArgName + nArgName) = '\0'; /* terminate arg name */

                while (SPACE(*x)) {
                    x++;
                }
                if (*x=='>' || *x==0) {
                    ArgVal = ArgName;
                    nArgVal = nArgName;
                } else if ((c=*x)=='\"' || c=='\'') {
                    register int cDelim = c;
                    x++;
                    ArgVal = x;
                    ampersandSeen = 0;
                    while ((c=*x)!=0 && c!=cDelim) {
                        if (c=='&') {
                            ampersandSeen = 1;
                        }
                        x++;
                    }
                    nArgVal = x - ArgVal;
                    if (c==0) {
                        RetError("Unterminated string",(ArgVal - xml - 1) );
                    } else {
                        x++;
                    }
                } else if (c!=0 && c!='>') {
                    ArgVal = x;
                    while ((c=*x)!=0 && c!='>' && !SPACE(c)) {
                        if (c=='&') {
                            ampersandSeen = 1;
                        }
                        x++;
                    }
                    if (c==0) {
                        RetError("Missing \">\"",(start-xml));
                    }
                    nArgVal = x - ArgVal;
                }

                
#ifdef TDOM_NS
                /*------------------------------------------------------------
                |   handle namespace attributes or normal ones
                \------------------------------------------------------------*/
                if (strncmp((char *)ArgName, "xmlns", 5) == 0) {
                    xmlns = ArgName;
                    newNS = 1;
                    
                    h = Tcl_CreateHashEntry(&HASHTAB(doc, tdom_attrNames),
                                            ArgName, &hnew); 
                    attrnode = (domAttrNode*) domAlloc(sizeof(domAttrNode));
                    memset(attrnode, 0, sizeof(domAttrNode));
                    attrnode->parentNode  = node;
                    attrnode->nodeName    = (char *)&(h->key);
                    attrnode->nodeType    = ATTRIBUTE_NODE;
                    attrnode->nodeFlags   = IS_NS_NODE;
                    attrnode->nodeValue   = (char*)MALLOC(nArgVal+1);
                    attrnode->valueLength = nArgVal;
                    memmove(attrnode->nodeValue, ArgVal, nArgVal);
                    *(attrnode->nodeValue + nArgVal) = 0;
                    if (ampersandSeen) {
                        if (!TranslateEntityRefs(attrnode->nodeValue,
                                                 &(attrnode->valueLength) )) {
                            RetError("Entity parsing error",(start-xml));
                        }
                    }
                    
                    if (xmlns[5] == ':') {
                        if (domIsNamespaceInScope (activeNS, activeNSpos,
                                                   &(xmlns[6]),
                                                   (char*)attrnode->nodeValue))
                        {
                            ns = domLookupPrefix (node, &(xmlns[6]));
                            newNS = 0;
                        } else {
                            ns = domNewNamespace(doc, &(xmlns[6]),
                                                 (char*)attrnode->nodeValue);
                        }
                    } else {
                        ns = domNewNamespace(doc, "", 
                                             (char*)attrnode->nodeValue);
                    }
                    attrnode->namespace   = ns->index;
                    if (newNS) {
                        /* push active namespace */
                        activeNSpos++;
                        if (activeNSpos >= activeNSsize) {
                            activeNS = (domActiveNS*) REALLOC(
                                           (char*)activeNS,
                                           sizeof(domActiveNS) * 2 * activeNSsize);
                            activeNSsize = 2 * activeNSsize;
                        }
                        activeNS[activeNSpos].depth     = depth;
                        activeNS[activeNSpos].namespace = ns;
                    }
    
                    if (NSattrList) {
                        lastNSAttr->nextSibling = attrnode;
                    } else {
                        NSattrList = attrnode;
                    }
                    lastNSAttr = attrnode;
                    

                } else {
#endif
                
                    /*------------------------------------------------------------
                    |   allocate new attribute node
                    \------------------------------------------------------------*/
                    h = Tcl_CreateHashEntry(&HASHTAB(doc,tdom_attrNames),
                                            ArgName, &hnew);
                    attrnode = (domAttrNode*) domAlloc(sizeof(domAttrNode));
                    memset(attrnode, 0, sizeof(domAttrNode));
                    attrnode->parentNode  = node;
                    attrnode->nodeName    = (char *)&(h->key);
                    attrnode->nodeType    = ATTRIBUTE_NODE;
                    attrnode->nodeValue   = (char*)MALLOC(nArgVal+1);
                    attrnode->valueLength = nArgVal;
                    memmove(attrnode->nodeValue, ArgVal, nArgVal);
                    *(attrnode->nodeValue + nArgVal) = 0;
                    if (ampersandSeen) {
                        if (!TranslateEntityRefs(attrnode->nodeValue,
                                                 &(attrnode->valueLength) )) {
                            RetError("Entity parsing error", (start - xml));
                        }
                    }
                    if (attrList) {
                        lastAttr->nextSibling = attrnode;
                    } else {
                        attrList = attrnode;
                    }
                    lastAttr = attrnode;
#ifdef TDOM_NS
                }
#endif 
                *(ArgName + nArgName) = saved;
                while (SPACE(*x)) {
                    x++;
                }
            }

#ifdef TDOM_NS
            /*----------------------------------------------------------
            |   look for namespace of element
            \---------------------------------------------------------*/
            domSplitQName (node->nodeName, tagPrefix,
                           &localname);
            for (nspos = activeNSpos; nspos >= 0; nspos--) {
                if (  ((tagPrefix[0] == '\0') && (activeNS[nspos].namespace->prefix[0] == '\0'))
                      || ((tagPrefix[0] != '\0') && (activeNS[nspos].namespace->prefix[0] != '\0')
                          && (strcmp(tagPrefix, activeNS[nspos].namespace->prefix) == 0))
                    ) {
                    if (activeNS[nspos].namespace->prefix[0] == '\0'
                        && activeNS[nspos].namespace->uri[0] == '\0'
                        && tagPrefix[0] == '\0') 
                    {
                        /* xml-names rec. 5.2: "The default namespace can be
                           set to the empty string. This has the same effect,
                           within the scope of the declaration, of there being
                           no default namespace." */
                        break;
                    }
                    node->namespace = activeNS[nspos].namespace->index;
                    DBG(fprintf(stderr, "tag='%s' uri='%s' \n",node->nodeName,
                                activeNS[nspos].namespace->uri);
                               )
                    break;
                }
            }

            /*----------------------------------------------------------
            |   look for attribute namespace
            \---------------------------------------------------------*/
            attrnode = attrList;
            while (attrnode) {
                domSplitQName ((char*)attrnode->nodeName, prefix, &localname);
                if (prefix[0] != '\0') {
                    for (nspos = activeNSpos; nspos >= 0; nspos--) {
                        if (  ((prefix[0] == '\0') && (activeNS[nspos].namespace->prefix[0] == '\0'))
                              || ((prefix[0] != '\0') && (activeNS[nspos].namespace->prefix[0] != '\0')
                                  && (strcmp(prefix, activeNS[nspos].namespace->prefix) == 0))
                            ) {
                            attrnode->namespace = activeNS[nspos].namespace->index;
                            DBG(fprintf(stderr, "attr='%s' uri='%s' \n",
                                        attrnode->nodeName,
                                        activeNS[nspos].namespace->uri);
                                )
                            break;
                        }
                    }
                }
                attrnode = attrnode->nextSibling;
            }
            if (lastNSAttr) {
                node->firstAttr = NSattrList;
                lastNSAttr->nextSibling = attrList;
            } else {
                node->firstAttr = attrList;
            }
#else
            node->firstAttr = attrList;

#endif
            if (*x=='/') {
                hasContent = 0;
                x++;
                if (*x!='>') {
                    RetError("Syntax Error",(x - xml - 1) );
                }
#ifdef TDOM_NS 
                /* pop active namespaces */
                while ( (activeNSpos >= 0) &&
                        (activeNS[activeNSpos].depth == depth) )
                {
                    activeNSpos--;
                } 
#endif                                   
            }
            if (x[1] == 0) {
#ifdef TDOM_NS
                FREE ((char *) activeNS);
#endif                
                return TCL_OK;
            }
            if (*x=='>') {
                x++;
            }
            if (hasContent) {
#ifdef TDOM_NS
                depth++;
#endif
                /*------------------------------------------------------------
                |   recurs to read child tags/texts
                \-----------------------------------------------------------*/
                parent_node = node;
            }
        }
    }
    if (forest && parent_node == parent) {
        FREE ((char *) activeNS);
        return TCL_OK;
    }
    RetError("Unexpected end",(x - xml) );

} /* XML_SimpleParse */



/*----------------------------------------------------------------------------
|   XML_SimpleParseDocument
|
|       Create a document, parses the XML string starting at 'pos' and
|       continuing to the first encountered error.
|
\---------------------------------------------------------------------------*/
domDocument *
XML_SimpleParseDocument (
    char    *xml,              /* Complete text of the file being parsed  */
    int      ignoreWhiteSpaces,
    int      keepCDATA,
    int      forest,
    char    *baseURI,
    Tcl_Obj *extResolver,
    int     *pos,
    char   **errStr
) {
    domDocument   *doc = domCreateDoc(baseURI, 0);
    domNode *node = NULL;
    Tcl_HashEntry *h;
    int hnew;
    
    if (extResolver) {
        doc->extResolver = tdomstrdup (Tcl_GetString (extResolver));
    }

    if (forest) {
        // Create umbreall tag
        h = Tcl_CreateHashEntry(&HASHTAB(doc,tdom_tagNames), "forestroot",
                                &hnew);
        node = (domNode*) domAlloc(sizeof(domNode));
        memset(node, 0, sizeof(domNode));
        node->nodeType      = ELEMENT_NODE;
        node->nodeName      = (char *)&(h->key);
        node->ownerDocument = doc;
        doc->rootNode->firstChild = node;
        doc->rootNode->lastChild = node;
    }
    
    *pos = 0;
    XML_SimpleParse (xml, pos, doc, node, ignoreWhiteSpaces, keepCDATA,
                     forest, errStr);
    if (forest) {
        doc->rootNode->firstChild = node->firstChild;
        doc->rootNode->lastChild = node->lastChild;
        domFree ((void*)node);
    }
    domSetDocumentElement (doc);

    return doc;

} /* XML_SimpleParseDocument */