-
Notifications
You must be signed in to change notification settings - Fork 0
/
xmlParser.cpp
2596 lines (2357 loc) · 94.7 KB
/
xmlParser.cpp
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
/**
****************************************************************************
* <P> XML.c - implementation file for basic XML parser written in ANSI C++
* for portability. It works by using recursion and a node tree for breaking
* down the elements of an XML document. </P>
*
* @version V2.24
* @author Frank Vanden Berghen
*
* NOTE:
*
* If you add "#define STRICT_PARSING", on the first line of this file
* the parser will see the following XML-stream:
* <a><b>some text</b><b>other text </a>
* as an error. Otherwise, this tring will be equivalent to:
* <a><b>some text</b><b>other text</b></a>
*
* NOTE:
*
* If you add "#define APPROXIMATE_PARSING" on the first line of this file
* the parser will see the following XML-stream:
* <data name="n1">
* <data name="n2">
* <data name="n3" />
* as equivalent to the following XML-stream:
* <data name="n1" />
* <data name="n2" />
* <data name="n3" />
* This can be useful for badly-formed XML-streams but prevent the use
* of the following XML-stream (problem is: tags at contiguous levels
* have the same names):
* <data name="n1">
* <data name="n2">
* <data name="n3" />
* </data>
* </data>
*
* NOTE:
*
* If you add "#define _XMLPARSER_NO_MESSAGEBOX_" on the first line of this file
* the "openFileHelper" function will always display error messages inside the
* console instead of inside a message-box-window. Message-box-windows are
* available on windows 9x/NT/2000/XP/Vista only.
*
* BSD license:
* Copyright (c) 2002, Frank Vanden Berghen
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Frank Vanden Berghen nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************
*/
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE
#endif
#include "xmlParser.h"
#ifdef _XMLWINDOWS
//#ifdef _DEBUG
//#define _CRTDBG_MAP_ALLOC
//#include <crtdbg.h>
//#endif
#define WIN32_LEAN_AND_MEAN
#include <Windows.h> // to have IsTextUnicode, MultiByteToWideChar, WideCharToMultiByte to handle unicode files
// to have "MessageBoxA" to display error messages for openFilHelper
#endif
#include <memory.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
XMLCSTR XMLNode::getVersion() { return _T("v2.23"); }
void free_XMLDLL(void *t){free(t);}
static char strictUTF8Parsing=1, guessUnicodeChars=1, dropWhiteSpace=1;
inline int mmin( const int t1, const int t2 ) { return t1 < t2 ? t1 : t2; }
// You can modify the initialization of the variable "XMLClearTags" below
// to change the clearTags that are currently recognized by the library.
// The number on the second columns is the length of the string inside the
// first column. The "<!DOCTYPE" declaration must be the second in the list.
static ALLXMLClearTag XMLClearTags[] =
{
{ _T("<![CDATA["),9, _T("]]>") },
{ _T("<!DOCTYPE"),9, _T(">") },
{ _T("<PRE>") ,5, _T("</PRE>") },
{ _T("<Script>") ,8, _T("</Script>")},
{ _T("<!--") ,4, _T("-->") },
{ NULL ,0, NULL }
};
ALLXMLClearTag* XMLNode::getClearTagTable() { return XMLClearTags; }
// You can modify the initialization of the variable "XMLEntities" below
// to change the character entities that are currently recognized by the library.
// The number on the second columns is the length of the string inside the
// first column. Additionally, the syntaxes " " and " " are recognized.
typedef struct { XMLCSTR s; int l; XMLCHAR c;} XMLCharacterEntity;
static XMLCharacterEntity XMLEntities[] =
{
{ _T("&" ), 5, _T('&' )},
{ _T("<" ), 4, _T('<' )},
{ _T(">" ), 4, _T('>' )},
{ _T("""), 6, _T('\"')},
{ _T("'"), 6, _T('\'')},
{ NULL , 0, '\0' }
};
// When rendering the XMLNode to a string (using the "createXMLString" function),
// you can ask for a beautiful formatting. This formatting is using the
// following indentation character:
#define INDENTCHAR _T('\t')
// The following function parses the XML errors into a user friendly string.
// You can edit this to change the output language of the library to something else.
XMLCSTR XMLNode::getError(XMLError xerror)
{
switch (xerror)
{
case eXMLErrorNone: return _T("No error");
case eXMLErrorMissingEndTag: return _T("Warning: Unmatched end tag");
case eXMLErrorEmpty: return _T("Error: No XML data");
case eXMLErrorFirstNotStartTag: return _T("Error: First token not start tag");
case eXMLErrorMissingTagName: return _T("Error: Missing start tag name");
case eXMLErrorMissingEndTagName: return _T("Error: Missing end tag name");
case eXMLErrorNoMatchingQuote: return _T("Error: Unmatched quote");
case eXMLErrorUnmatchedEndTag: return _T("Error: Unmatched end tag");
case eXMLErrorUnmatchedEndClearTag: return _T("Error: Unmatched clear tag end");
case eXMLErrorUnexpectedToken: return _T("Error: Unexpected token found");
case eXMLErrorInvalidTag: return _T("Error: Invalid tag found");
case eXMLErrorNoElements: return _T("Error: No elements found");
case eXMLErrorFileNotFound: return _T("Error: File not found");
case eXMLErrorFirstTagNotFound: return _T("Error: First Tag not found");
case eXMLErrorUnknownCharacterEntity:return _T("Error: Unknown character entity");
case eXMLErrorCharConversionError: return _T("Error: unable to convert between UNICODE and MultiByte chars");
case eXMLErrorCannotOpenWriteFile: return _T("Error: unable to open file for writing");
case eXMLErrorCannotWriteFile: return _T("Error: cannot write into file");
case eXMLErrorBase64DataSizeIsNotMultipleOf4: return _T("Warning: Base64-string length is not a multiple of 4");
case eXMLErrorBase64DecodeTruncatedData: return _T("Warning: Base64-string is truncated");
case eXMLErrorBase64DecodeIllegalCharacter: return _T("Error: Base64-string contains an illegal character");
case eXMLErrorBase64DecodeBufferTooSmall: return _T("Error: Base64 decode output buffer is too small");
};
return _T("Unknown");
}
// Here is an abstraction layer to access some common string manipulation functions.
// The abstraction layer is currently working for gcc, Microsoft Visual Studio 6.0,
// Microsoft Visual Studio .NET, CC (sun compiler) and Borland C++.
// If you plan to "port" the library to a new system/compiler, all you have to do is
// to edit the following lines.
#ifdef XML_NO_WIDE_CHAR
char myIsTextUnicode(const void *b, int len) { return FALSE; }
#else
#if defined (UNDER_CE) || !defined(WIN32)
char myIsTextUnicode(const void *b, int len) // inspired by the Wine API: RtlIsTextUnicode
{
#ifdef sun
// for SPARC processors: wchar_t* buffers must always be alligned, otherwise it's a char* buffer.
if ((((unsigned long)b)%sizeof(wchar_t))!=0) return FALSE;
#endif
const wchar_t *s=(const wchar_t*)b;
// buffer too small:
if (len<(int)sizeof(wchar_t)) return FALSE;
// odd length test
if (len&1) return FALSE;
/* only checks the first 256 characters */
len=mmin(256,len/sizeof(wchar_t));
// Check for the special byte order:
if (*s == 0xFFFE) return FALSE; // IS_TEXT_UNICODE_REVERSE_SIGNATURE;
if (*s == 0xFEFF) return TRUE; // IS_TEXT_UNICODE_SIGNATURE
// checks for ASCII characters in the UNICODE stream
int i,stats=0;
for (i=0; i<len; i++) if (s[i]<=(unsigned short)255) stats++;
if (stats>len/2) return TRUE;
// Check for UNICODE NULL chars
for (i=0; i<len; i++) if (!s[i]) return TRUE;
return FALSE;
}
#else
char myIsTextUnicode(const void *b,int l) { return (char)IsTextUnicode((CONST LPVOID)b,l,NULL); };
#endif
#endif
#ifdef _XMLWINDOWS
// for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET,
#ifdef _XMLUNICODE
wchar_t *myMultiByteToWideChar(const char *s,int l)
{
int i;
if (strictUTF8Parsing) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,l,NULL,0);
else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,l,NULL,0);
if (i<0) return NULL;
wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(XMLCHAR));
if (strictUTF8Parsing) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,l,d,i);
else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,l,d,i);
d[i]=0;
return d;
}
#else
char *myWideCharToMultiByte(const wchar_t *s,int l)
{
UINT codePage=CP_ACP; if (strictUTF8Parsing) codePage=CP_UTF8;
int i=(int)WideCharToMultiByte(codePage, // code page
0, // performance and mapping flags
s, // wide-character string
l, // number of chars in string
NULL, // buffer for new string
0, // size of buffer
NULL, // default for unmappable chars
NULL // set when default char used
);
if (i<0) return NULL;
char *d=(char*)malloc(i+1);
WideCharToMultiByte(codePage, // code page
0, // performance and mapping flags
s, // wide-character string
l, // number of chars in string
d, // buffer for new string
i, // size of buffer
NULL, // default for unmappable chars
NULL // set when default char used
);
d[i]=0;
return d;
}
#endif
#ifdef __BORLANDC__
int _strnicmp(char *c1, char *c2, int l){ return strnicmp(c1,c2,l);}
#endif
#else
// for gcc and CC
#ifdef XML_NO_WIDE_CHAR
char *myWideCharToMultiByte(const wchar_t *s, int l) { return NULL; }
#else
char *myWideCharToMultiByte(const wchar_t *s, int l)
{
const wchar_t *ss=s;
int i=(int)wcsrtombs(NULL,&ss,0,NULL);
if (i<0) return NULL;
char *d=(char *)malloc(i+1);
wcsrtombs(d,&s,i,NULL);
d[i]=0;
return d;
}
#endif
#ifdef _XMLUNICODE
wchar_t *myMultiByteToWideChar(const char *s, int l)
{
const char *ss=s;
int i=(int)mbsrtowcs(NULL,&ss,0,NULL);
if (i<0) return NULL;
wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(wchar_t));
mbsrtowcs(d,&s,l,NULL);
d[i]=0;
return d;
}
int _tcslen(XMLCSTR c) { return wcslen(c); }
#ifdef sun
// for CC
#include <widec.h>
int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncasecmp(c1,c2,l);}
int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return wscasecmp(c1,c2); }
#else
// for gcc
int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncasecmp(c1,c2,l);}
int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return wcscasecmp(c1,c2); }
#endif
XMLSTR _tcsstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
XMLSTR _tcscpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
FILE *_tfopen(XMLCSTR filename,XMLCSTR mode)
{
char *filenameAscii=myWideCharToMultiByte(filename,0);
FILE *f;
if (mode[0]==_T('r')) f=fopen(filenameAscii,"rb");
else f=fopen(filenameAscii,"wb");
free(filenameAscii);
return f;
}
#else
FILE *_tfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
int _tcslen(XMLCSTR c) { return strlen(c); }
int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncasecmp(c1,c2,l);}
int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return strcasecmp(c1,c2); }
XMLSTR _tcsstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
XMLSTR _tcscpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
#endif
int _strnicmp(const char *c1,const char *c2, int l) { return strncasecmp(c1,c2,l);}
#endif
/////////////////////////////////////////////////////////////////////////
// Here start the core implementation of the XMLParser library //
/////////////////////////////////////////////////////////////////////////
// You should normally not change anything below this point.
// For your own information, I suggest that you read the openFileHelper below:
XMLNode XMLNode::openFileHelper(XMLCSTR filename, XMLCSTR tag)
{
// guess the value of the global parameter "strictUTF8Parsing"
// (the guess is based on the first 200 bytes of the file).
FILE *f=_tfopen(filename,_T("rb"));
if (f)
{
char bb[205];
int l=(int)fread(bb,1,200,f);
setGlobalOptions(guessUnicodeChars,guessUTF8ParsingParameterValue(bb,l),dropWhiteSpace);
fclose(f);
}
// parse the file
XMLResults pResults;
XMLNode xnode=XMLNode::parseFile(filename,tag,&pResults);
// display error message (if any)
if (pResults.error != eXMLErrorNone)
{
// create message
char message[2000],*s1=(char*)"",*s3=(char*)""; XMLCSTR s2=_T("");
if (pResults.error==eXMLErrorFirstTagNotFound) { s1=(char*)"First Tag should be '"; s2=tag; s3=(char*)"'.\n"; }
sprintf(message,
#ifdef _XMLUNICODE
"XML Parsing error inside file '%S'.\n%S\nAt line %i, column %i.\n%s%S%s"
#else
"XML Parsing error inside file '%s'.\n%s\nAt line %i, column %i.\n%s%s%s"
#endif
,filename,XMLNode::getError(pResults.error),pResults.nLine,pResults.nColumn,s1,s2,s3);
// display message
#if defined(WIN32) && !defined(UNDER_CE) && !defined(_XMLPARSER_NO_MESSAGEBOX_)
MessageBoxA(NULL,message,"XML Parsing error",MB_OK|MB_ICONERROR|MB_TOPMOST);
#else
printf("%s",message);
#endif
exit(255);
}
return xnode;
}
#ifndef _XMLUNICODE
// If "strictUTF8Parsing=0" then we assume that all characters have the same length of 1 byte.
// If "strictUTF8Parsing=1" then the characters have different lengths (from 1 byte to 4 bytes).
// This table is used as lookup-table to know the length of a character (in byte) based on the
// content of the first byte of the character.
// (note: if you modify this, you must always have XML_utf8ByteTable[0]=0 ).
static const char XML_utf8ByteTable[256] =
{
// 0 1 2 3 4 5 6 7 8 9 a b c d e f
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70End of ASCII range
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 0x80 to 0xc1 invalid
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 0xc2 to 0xdf 2 byte
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,// 0xe0 0xe0 to 0xef 3 byte
4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid
};
static const char XML_asciiByteTable[256] =
{
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
};
static const char *XML_ByteTable=(const char *)XML_utf8ByteTable; // the default is "strictUTF8Parsing=1"
#endif
XMLError XMLNode::writeToFile(XMLCSTR filename, const char *encoding, char nFormat) const
{
if (!d) return eXMLErrorNone;
int i;
XMLSTR t=createXMLString(nFormat,&i);
FILE *f=_tfopen(filename,_T("wb"));
if (!f) return eXMLErrorCannotOpenWriteFile;
#ifdef _XMLUNICODE
unsigned char h[2]={ 0xFF, 0xFE };
if (!fwrite(h,2,1,f)) return eXMLErrorCannotWriteFile;
if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
{
if (!fwrite(_T("<?xml version=\"1.0\" encoding=\"utf-16\"?>\n"),sizeof(wchar_t)*40,1,f))
return eXMLErrorCannotWriteFile;
}
#else
if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
{
if ((!encoding)||(XML_ByteTable==XML_utf8ByteTable))
{
// header so that windows recognize the file as UTF-8:
unsigned char h[3]={0xEF,0xBB,0xBF};
if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
if (!fwrite("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",39,1,f)) return eXMLErrorCannotWriteFile;
}
else
if (fprintf(f,"<?xml version=\"1.0\" encoding=\"%s\"?>\n",encoding)<0) return eXMLErrorCannotWriteFile;
} else
{
if (XML_ByteTable==XML_utf8ByteTable) // test if strictUTF8Parsing==1"
{
unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
}
}
#endif
if (!fwrite(t,sizeof(XMLCHAR)*i,1,f)) return eXMLErrorCannotWriteFile;
if (fclose(f)!=0) return eXMLErrorCannotWriteFile;
free(t);
return eXMLErrorNone;
}
// Duplicate a given string.
XMLSTR stringDup(XMLCSTR lpszData, int cbData)
{
if (lpszData==NULL) return NULL;
XMLSTR lpszNew;
if (cbData==0) cbData=(int)_tcslen(lpszData);
lpszNew = (XMLSTR)malloc((cbData+1) * sizeof(XMLCHAR));
if (lpszNew)
{
memcpy(lpszNew, lpszData, (cbData) * sizeof(XMLCHAR));
lpszNew[cbData] = (XMLCHAR)NULL;
}
return lpszNew;
}
XMLNode XMLNode::emptyXMLNode;
XMLClear XMLNode::emptyXMLClear={ NULL, NULL, NULL};
XMLAttribute XMLNode::emptyXMLAttribute={ NULL, NULL};
// Enumeration used to decipher what type a token is
typedef enum XMLTokenTypeTag
{
eTokenText = 0,
eTokenQuotedText,
eTokenTagStart, /* "<" */
eTokenTagEnd, /* "</" */
eTokenCloseTag, /* ">" */
eTokenEquals, /* "=" */
eTokenDeclaration, /* "<?" */
eTokenShortHandClose, /* "/>" */
eTokenClear,
eTokenError
} XMLTokenType;
// Main structure used for parsing XML
typedef struct XML
{
XMLCSTR lpXML;
XMLCSTR lpszText;
int nIndex,nIndexMissigEndTag;
enum XMLError error;
XMLCSTR lpEndTag;
int cbEndTag;
XMLCSTR lpNewElement;
int cbNewElement;
int nFirst;
} XML;
typedef struct
{
ALLXMLClearTag *pClr;
XMLCSTR pStr;
} NextToken;
// Enumeration used when parsing attributes
typedef enum Attrib
{
eAttribName = 0,
eAttribEquals,
eAttribValue
} Attrib;
// Enumeration used when parsing elements to dictate whether we are currently
// inside a tag
typedef enum Status
{
eInsideTag = 0,
eOutsideTag
} Status;
// private (used while rendering):
XMLSTR toXMLString(XMLSTR dest,XMLCSTR source)
{
XMLSTR dd=dest;
XMLCHAR ch;
XMLCharacterEntity *entity;
while ((ch=*source))
{
entity=XMLEntities;
do
{
if (ch==entity->c) {_tcscpy(dest,entity->s); dest+=entity->l; source++; goto out_of_loop1; }
entity++;
} while(entity->s);
#ifdef _XMLUNICODE
*(dest++)=*(source++);
#else
switch(XML_ByteTable[(unsigned char)ch])
{
case 4: *(dest++)=*(source++);
case 3: *(dest++)=*(source++);
case 2: *(dest++)=*(source++);
case 1: *(dest++)=*(source++);
}
#endif
out_of_loop1:
;
}
*dest=0;
return dd;
}
// private (used while rendering):
int lengthXMLString(XMLCSTR source)
{
int r=0;
XMLCharacterEntity *entity;
XMLCHAR ch;
while ((ch=*source))
{
entity=XMLEntities;
do
{
if (ch==entity->c) { r+=entity->l; source++; goto out_of_loop1; }
entity++;
} while(entity->s);
#ifdef _XMLUNICODE
r++; source++;
#else
ch=XML_ByteTable[(unsigned char)ch]; r+=ch; source+=ch;
#endif
out_of_loop1:
;
}
return r;
}
XMLSTR toXMLString(XMLCSTR source)
{
XMLSTR dest=(XMLSTR)malloc((lengthXMLString(source)+1)*sizeof(XMLCHAR));
return toXMLString(dest,source);
}
XMLSTR toXMLStringFast(XMLSTR *dest,int *destSz, XMLCSTR source)
{
int l=lengthXMLString(source)+1;
if (l>*destSz) { *destSz=l; *dest=(XMLSTR)realloc(*dest,l*sizeof(XMLCHAR)); }
return toXMLString(*dest,source);
}
// private:
XMLSTR fromXMLString(XMLCSTR s, int lo, XML *pXML)
{
// This function is the opposite of the function "toXMLString". It decodes the escape
// sequences &, ", ', <, > and replace them by the characters
// &,",',<,>. This function is used internally by the XML Parser. All the calls to
// the XML library will always gives you back "decoded" strings.
//
// in: string (s) and length (lo) of string
// out: new allocated string converted from xml
if (!s) return NULL;
int ll=0,j;
XMLSTR d;
XMLCSTR ss=s;
XMLCharacterEntity *entity;
while ((lo>0)&&(*s))
{
if (*s==_T('&'))
{
if ((lo>2)&&(s[1]==_T('#')))
{
s+=2; lo-=2;
if ((*s==_T('X'))||(*s==_T('x'))) { s++; lo--; }
while ((*s)&&(*s!=_T(';'))&&((lo--)>0)) s++;
if (*s!=_T(';'))
{
pXML->error=eXMLErrorUnknownCharacterEntity;
return NULL;
}
s++; lo--;
} else
{
entity=XMLEntities;
do
{
if ((lo>=entity->l)&&(_tcsnicmp(s,entity->s,entity->l)==0)) { s+=entity->l; lo-=entity->l; break; }
entity++;
} while(entity->s);
if (!entity->s)
{
pXML->error=eXMLErrorUnknownCharacterEntity;
return NULL;
}
}
} else
{
#ifdef _XMLUNICODE
s++; lo--;
#else
j=XML_ByteTable[(unsigned char)*s]; s+=j; lo-=j; ll+=j-1;
#endif
}
ll++;
}
d=(XMLSTR)malloc((ll+1)*sizeof(XMLCHAR));
s=d;
while (ll-->0)
{
if (*ss==_T('&'))
{
if (ss[1]==_T('#'))
{
ss+=2; j=0;
if ((*ss==_T('X'))||(*ss==_T('x')))
{
ss++;
while (*ss!=_T(';'))
{
if ((*ss>=_T('0'))&&(*ss<=_T('9'))) j=(j<<4)+*ss-_T('0');
else if ((*ss>=_T('A'))&&(*ss<=_T('F'))) j=(j<<4)+*ss-_T('A')+10;
else if ((*ss>=_T('a'))&&(*ss<=_T('f'))) j=(j<<4)+*ss-_T('a')+10;
else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
ss++;
}
} else
{
while (*ss!=_T(';'))
{
if ((*ss>=_T('0'))&&(*ss<=_T('9'))) j=(j*10)+*ss-_T('0');
else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
ss++;
}
}
(*d++)=(XMLCHAR)j; ss++;
} else
{
entity=XMLEntities;
do
{
if (_tcsnicmp(ss,entity->s,entity->l)==0) { *(d++)=entity->c; ss+=entity->l; break; }
entity++;
} while(entity->s);
}
} else
{
#ifdef _XMLUNICODE
*(d++)=*(ss++);
#else
switch(XML_ByteTable[(unsigned char)*ss])
{
case 4: *(d++)=*(ss++); ll--;
case 3: *(d++)=*(ss++); ll--;
case 2: *(d++)=*(ss++); ll--;
case 1: *(d++)=*(ss++);
}
#endif
}
}
*d=0;
return (XMLSTR)s;
}
#define XML_isSPACECHAR(ch) ((ch==_T('\n'))||(ch==_T(' '))||(ch== _T('\t'))||(ch==_T('\r')))
// private:
char myTagCompare(XMLCSTR cclose, XMLCSTR copen)
// !!!! WARNING strange convention&:
// return 0 if equals
// return 1 if different
{
if (!cclose) return 1;
int l=(int)_tcslen(cclose);
if (_tcsnicmp(cclose, copen, l)!=0) return 1;
const XMLCHAR c=copen[l];
if (XML_isSPACECHAR(c)||
(c==_T('/' ))||
(c==_T('<' ))||
(c==_T('>' ))||
(c==_T('=' ))) return 0;
return 1;
}
// Obtain the next character from the string.
static inline XMLCHAR getNextChar(XML *pXML)
{
XMLCHAR ch = pXML->lpXML[pXML->nIndex];
#ifdef _XMLUNICODE
if (ch!=0) pXML->nIndex++;
#else
pXML->nIndex+=XML_ByteTable[(unsigned char)ch];
#endif
return ch;
}
// Find the next token in a string.
// pcbToken contains the number of characters that have been read.
static NextToken GetNextToken(XML *pXML, int *pcbToken, enum XMLTokenTypeTag *pType)
{
NextToken result;
XMLCHAR ch;
XMLCHAR chTemp;
int indexStart,nFoundMatch,nIsText=FALSE;
result.pClr=NULL; // prevent warning
// Find next non-white space character
do { indexStart=pXML->nIndex; ch=getNextChar(pXML); } while XML_isSPACECHAR(ch);
if (ch)
{
// Cache the current string pointer
result.pStr = &pXML->lpXML[indexStart];
// First check whether the token is in the clear tag list (meaning it
// does not need formatting).
ALLXMLClearTag *ctag=XMLClearTags;
do
{
if (_tcsnicmp(ctag->lpszOpen, result.pStr, ctag->openTagLen)==0)
{
result.pClr=ctag;
pXML->nIndex+=ctag->openTagLen-1;
*pType=eTokenClear;
return result;
}
ctag++;
} while(ctag->lpszOpen);
// If we didn't find a clear tag then check for standard tokens
switch(ch)
{
// Check for quotes
case _T('\''):
case _T('\"'):
// Type of token
*pType = eTokenQuotedText;
chTemp = ch;
// Set the size
nFoundMatch = FALSE;
// Search through the string to find a matching quote
while((ch = getNextChar(pXML)))
{
if (ch==chTemp) { nFoundMatch = TRUE; break; }
if (ch==_T('<')) break;
}
// If we failed to find a matching quote
if (nFoundMatch == FALSE)
{
pXML->nIndex=indexStart+1;
nIsText=TRUE;
break;
}
// 4.02.2002
// if (FindNonWhiteSpace(pXML)) pXML->nIndex--;
break;
// Equals (used with attribute values)
case _T('='):
*pType = eTokenEquals;
break;
// Close tag
case _T('>'):
*pType = eTokenCloseTag;
break;
// Check for tag start and tag end
case _T('<'):
// Peek at the next character to see if we have an end tag '</',
// or an xml declaration '<?'
chTemp = pXML->lpXML[pXML->nIndex];
// If we have a tag end...
if (chTemp == _T('/'))
{
// Set the type and ensure we point at the next character
getNextChar(pXML);
*pType = eTokenTagEnd;
}
// If we have an XML declaration tag
else if (chTemp == _T('?'))
{
// Set the type and ensure we point at the next character
getNextChar(pXML);
*pType = eTokenDeclaration;
}
// Otherwise we must have a start tag
else
{
*pType = eTokenTagStart;
}
break;
// Check to see if we have a short hand type end tag ('/>').
case _T('/'):
// Peek at the next character to see if we have a short end tag '/>'
chTemp = pXML->lpXML[pXML->nIndex];
// If we have a short hand end tag...
if (chTemp == _T('>'))
{
// Set the type and ensure we point at the next character
getNextChar(pXML);
*pType = eTokenShortHandClose;
break;
}
// If we haven't found a short hand closing tag then drop into the
// text process
// Other characters
default:
nIsText = TRUE;
}
// If this is a TEXT node
if (nIsText)
{
// Indicate we are dealing with text
*pType = eTokenText;
while((ch = getNextChar(pXML)))
{
if XML_isSPACECHAR(ch)
{
indexStart++; break;
} else if (ch==_T('/'))
{
// If we find a slash then this maybe text or a short hand end tag
// Peek at the next character to see it we have short hand end tag
ch=pXML->lpXML[pXML->nIndex];
// If we found a short hand end tag then we need to exit the loop
if (ch==_T('>')) { pXML->nIndex--; break; }
} else if ((ch==_T('<'))||(ch==_T('>'))||(ch==_T('=')))
{
pXML->nIndex--; break;
}
}
}
*pcbToken = pXML->nIndex-indexStart;
} else
{
// If we failed to obtain a valid character
*pcbToken = 0;
*pType = eTokenError;
result.pStr=NULL;
}
return result;
}
XMLCSTR XMLNode::updateName_WOSD(XMLCSTR lpszName)
{
if (d->lpszName&&(lpszName!=d->lpszName)) free((void*)d->lpszName);
d->lpszName=lpszName;
return lpszName;
}
// private:
XMLNode::XMLNode(struct XMLNodeDataTag *p){ d=p; (p->ref_count)++; }
XMLNode::XMLNode(XMLNodeData *pParent, XMLCSTR lpszName, char isDeclaration)
{
d=(XMLNodeData*)malloc(sizeof(XMLNodeData));
d->ref_count=1;
d->lpszName=NULL;
d->nChild= 0;
d->nText = 0;
d->nClear = 0;
d->nAttribute = 0;
d->isDeclaration = isDeclaration;
d->pParent = pParent;
d->pChild= NULL;
d->pText= NULL;
d->pClear= NULL;
d->pAttribute= NULL;
d->pOrder= NULL;
updateName_WOSD(lpszName);
}
XMLNode XMLNode::createXMLTopNode_WOSD(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,lpszName,isDeclaration); }
XMLNode XMLNode::createXMLTopNode(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,stringDup(lpszName),isDeclaration); }
#define MEMORYINCREASE 50
static inline void *myRealloc(void *p, int newsize, int memInc, int sizeofElem)
{
if (p==NULL) { if (memInc) return malloc(memInc*sizeofElem); return malloc(sizeofElem); }
if ((memInc==0)||((newsize%memInc)==0)) p=realloc(p,(newsize+memInc)*sizeofElem);
// if (!p)
// {
// printf("XMLParser Error: Not enough memory! Aborting...\n"); exit(220);
// }
return p;
}
// private:
int XMLNode::findPosition(XMLNodeData *d, int index, XMLElementType xtype)
{
if (index<0) return -1;
int i=0,j=(int)((index<<2)+xtype),*o=d->pOrder; while (o[i]!=j) i++; return i;
}
// private:
// update "order" information when deleting a content of a XMLNode
int XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index)
{
int n=d->nChild+d->nText+d->nClear, *o=d->pOrder,i=findPosition(d,index,t);
memmove(o+i, o+i+1, (n-i)*sizeof(int));
for (;i<n;i++)
if ((o[i]&3)==(int)t) o[i]-=4;
// We should normally do:
// d->pOrder=(int)realloc(d->pOrder,n*sizeof(int));
// but we skip reallocation because it's too time consuming.
// Anyway, at the end, it will be free'd completely at once.
return i;
}
void *XMLNode::addToOrder(int memoryIncrease,int *_pos, int nc, void *p, int size, XMLElementType xtype)
{
// in: *_pos is the position inside d->pOrder ("-1" means "EndOf")
// out: *_pos is the index inside p
p=myRealloc(p,(nc+1),memoryIncrease,size);
int n=d->nChild+d->nText+d->nClear;
d->pOrder=(int*)myRealloc(d->pOrder,n+1,memoryIncrease*3,sizeof(int));
int pos=*_pos,*o=d->pOrder;
if ((pos<0)||(pos>=n)) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
int i=pos;
memmove(o+i+1, o+i, (n-i)*sizeof(int));
while ((pos<n)&&((o[pos]&3)!=(int)xtype)) pos++;
if (pos==n) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
o[i]=o[pos];
for (i=pos+1;i<=n;i++) if ((o[i]&3)==(int)xtype) o[i]+=4;
*_pos=pos=o[pos]>>2;
memmove(((char*)p)+(pos+1)*size,((char*)p)+pos*size,(nc-pos)*size);
return p;
}
// Add a child node to the given element.
XMLNode XMLNode::addChild_priv(int memoryIncrease, XMLCSTR lpszName, char isDeclaration, int pos)
{
if (!lpszName) return emptyXMLNode;