]> Creatis software - bbtk.git/blob - kernel/src/xmlParser.cpp
fb98935cb014feab7d7a84d2b342503c2446ae66
[bbtk.git] / kernel / src / xmlParser.cpp
1 /**
2  ****************************************************************************
3  * <P> XML.c - implementation file for basic XML parser written in ANSI C++
4  * for portability. It works by using recursion and a node tree for breaking
5  * down the elements of an XML document.  </P>
6  *
7  * @version     V2.23
8  * @author      Frank Vanden Berghen
9  *
10  * NOTE:
11  *
12  *   If you add "#define STRICT_PARSING", on the first line of this file
13  *   the parser will see the following XML-stream:
14  *      <a><b>some text</b><b>other text    </a>
15  *   as an error. Otherwise, this tring will be equivalent to:
16  *      <a><b>some text</b><b>other text</b></a>
17  *
18  * NOTE:
19  *
20  *   If you add "#define APPROXIMATE_PARSING" on the first line of this file
21  *   the parser will see the following XML-stream:
22  *     <data name="n1">
23  *     <data name="n2">
24  *     <data name="n3" />
25  *   as equivalent to the following XML-stream:
26  *     <data name="n1" />
27  *     <data name="n2" />
28  *     <data name="n3" />
29  *   This can be useful for badly-formed XML-streams but prevent the use
30  *   of the following XML-stream (problem is: tags at contiguous levels
31  *   have the same names):
32  *     <data name="n1">
33  *        <data name="n2">
34  *            <data name="n3" />
35  *        </data>
36  *     </data>
37  *
38  * NOTE:
39  *
40  *   If you add "#define _XMLPARSER_NO_MESSAGEBOX_" on the first line of this file
41  *   the "openFileHelper" function will always display error messages inside the
42  *   console instead of inside a message-box-window. Message-box-windows are
43  *   available on windows 9x/NT/2000/XP/Vista only.
44  *
45  * BSD license:
46  * Copyright (c) 2002, Frank Vanden Berghen
47  * All rights reserved.
48  * Redistribution and use in source and binary forms, with or without
49  * modification, are permitted provided that the following conditions are met:
50  *
51  *     * Redistributions of source code must retain the above copyright
52  *       notice, this list of conditions and the following disclaimer.
53  *     * Redistributions in binary form must reproduce the above copyright
54  *       notice, this list of conditions and the following disclaimer in the
55  *       documentation and/or other materials provided with the distribution.
56  *     * Neither the name of the Frank Vanden Berghen nor the
57  *       names of its contributors may be used to endorse or promote products
58  *       derived from this software without specific prior written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
61  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
62  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
63  * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
64  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
65  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
66  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
67  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
69  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
70  *
71  ****************************************************************************
72  */
73 #ifndef _CRT_SECURE_NO_DEPRECATE
74 #define _CRT_SECURE_NO_DEPRECATE
75 #endif
76 #include "xmlParser.h"
77 #ifdef _XMLWINDOWS
78 //#ifdef _DEBUG
79 //#define _CRTDBG_MAP_ALLOC
80 //#include <crtdbg.h>
81 //#endif
82 #define WIN32_LEAN_AND_MEAN
83 #include <Windows.h> // to have IsTextUnicode, MultiByteToWideChar, WideCharToMultiByte to handle unicode files
84                      // to have "MessageBoxA" to display error messages for openFilHelper
85 #endif
86
87 #include <memory.h>
88 #include <assert.h>
89 #include <stdio.h>
90 #include <string.h>
91 #include <stdlib.h>
92
93 XMLCSTR XMLNode::getVersion() { return _T("v2.23"); }
94 void free_XMLDLL(void *t){free(t);}
95
96 static char strictUTF8Parsing=1, guessUnicodeChars=1, dropWhiteSpace=1;
97
98 inline int mmin( const int t1, const int t2 ) { return t1 < t2 ? t1 : t2; }
99
100 // You can modify the initialization of the variable "XMLClearTags" below
101 // to change the clearTags that are currently recognized by the library.
102 // The number on the second columns is the length of the string inside the
103 // first column. The "<!DOCTYPE" declaration must be the second in the list.
104 static ALLXMLClearTag XMLClearTags[] =
105 {
106     {    _T("<![CDATA["),9,  _T("]]>")      },
107     {    _T("<!DOCTYPE"),9,  _T(">")        },
108     {    _T("<PRE>")    ,5,  _T("</PRE>")   },
109     {    _T("<Script>") ,8,  _T("</Script>")},
110     {    _T("<!--")     ,4,  _T("-->")      },
111     {    NULL           ,0,  NULL           }
112 };
113 ALLXMLClearTag* XMLNode::getClearTagTable() { return XMLClearTags; }
114
115 // You can modify the initialization of the variable "XMLEntities" below
116 // to change the character entities that are currently recognized by the library.
117 // The number on the second columns is the length of the string inside the
118 // first column. Additionally, the syntaxes "&#xA0;" and "&#160;" are recognized.
119 typedef struct { XMLCSTR s; int l; XMLCHAR c;} XMLCharacterEntity;
120 static XMLCharacterEntity XMLEntities[] =
121 {
122     { _T("&amp;" ), 5, _T('&' )},
123     { _T("&lt;"  ), 4, _T('<' )},
124     { _T("&gt;"  ), 4, _T('>' )},
125     { _T("&quot;"), 6, _T('\"')},
126     { _T("&apos;"), 6, _T('\'')},
127     { NULL        , 0, '\0'    }
128 };
129
130 // When rendering the XMLNode to a string (using the "createXMLString" function),
131 // you can ask for a beautiful formatting. This formatting is using the
132 // following indentation character:
133 #define INDENTCHAR _T('\t')
134
135 // The following function parses the XML errors into a user friendly string.
136 // You can edit this to change the output language of the library to something else.
137 XMLCSTR XMLNode::getError(XMLError xerror)
138 {
139     switch (xerror)
140     {
141     case eXMLErrorNone:                  return _T("No error");
142     case eXMLErrorMissingEndTag:         return _T("Warning: Unmatched end tag");
143     case eXMLErrorEmpty:                 return _T("Error: No XML data");
144     case eXMLErrorFirstNotStartTag:      return _T("Error: First token not start tag");
145     case eXMLErrorMissingTagName:        return _T("Error: Missing start tag name");
146     case eXMLErrorMissingEndTagName:     return _T("Error: Missing end tag name");
147     case eXMLErrorNoMatchingQuote:       return _T("Error: Unmatched quote");
148     case eXMLErrorUnmatchedEndTag:       return _T("Error: Unmatched end tag");
149     case eXMLErrorUnmatchedEndClearTag:  return _T("Error: Unmatched clear tag end");
150     case eXMLErrorUnexpectedToken:       return _T("Error: Unexpected token found");
151     case eXMLErrorInvalidTag:            return _T("Error: Invalid tag found");
152     case eXMLErrorNoElements:            return _T("Error: No elements found");
153     case eXMLErrorFileNotFound:          return _T("Error: File not found");
154     case eXMLErrorFirstTagNotFound:      return _T("Error: First Tag not found");
155     case eXMLErrorUnknownCharacterEntity:return _T("Error: Unknown character entity");
156     case eXMLErrorCharConversionError:   return _T("Error: unable to convert between UNICODE and MultiByte chars");
157     case eXMLErrorCannotOpenWriteFile:   return _T("Error: unable to open file for writing");
158     case eXMLErrorCannotWriteFile:       return _T("Error: cannot write into file");
159
160     case eXMLErrorBase64DataSizeIsNotMultipleOf4: return _T("Warning: Base64-string length is not a multiple of 4");
161     case eXMLErrorBase64DecodeTruncatedData:      return _T("Warning: Base64-string is truncated");
162     case eXMLErrorBase64DecodeIllegalCharacter:   return _T("Error: Base64-string contains an illegal character");
163     case eXMLErrorBase64DecodeBufferTooSmall:     return _T("Error: Base64 decode output buffer is too small");
164     };
165     return _T("Unknown");
166 }
167
168 // Here is an abstraction layer to access some common string manipulation functions.
169 // The abstraction layer is currently working for gcc, Microsoft Visual Studio 6.0,
170 // Microsoft Visual Studio .NET, CC (sun compiler) and Borland C++.
171 // If you plan to "port" the library to a new system/compiler, all you have to do is
172 // to edit the following lines.
173 #ifdef XML_NO_WIDE_CHAR
174 char myIsTextUnicode(const void *b, int len) { return FALSE; }
175 #else
176     #if defined (UNDER_CE) || !defined(WIN32)
177     char myIsTextUnicode(const void *b, int len) // inspired by the Wine API: RtlIsTextUnicode
178     {
179 #ifdef sun
180         // for SPARC processors: wchar_t* buffers must always be alligned, otherwise it's a char* buffer.
181         if ((((unsigned long)b)%sizeof(wchar_t))!=0) return FALSE;
182 #endif
183         const wchar_t *s=(const wchar_t*)b;
184
185         // buffer too small:
186         if (len<(int)sizeof(wchar_t)) return FALSE;
187
188         // odd length test
189         if (len&1) return FALSE;
190
191         /* only checks the first 256 characters */
192         len=mmin(256,len/sizeof(wchar_t));
193
194         // Check for the special byte order:
195         if (*s == 0xFFFE) return FALSE;     // IS_TEXT_UNICODE_REVERSE_SIGNATURE;
196         if (*s == 0xFEFF) return TRUE;      // IS_TEXT_UNICODE_SIGNATURE
197
198         // checks for ASCII characters in the UNICODE stream
199         int i,stats=0;
200         for (i=0; i<len; i++) if (s[i]<=(unsigned short)255) stats++;
201         if (stats>len/2) return TRUE;
202
203         // Check for UNICODE NULL chars
204         for (i=0; i<len; i++) if (!s[i]) return TRUE;
205
206         return FALSE;
207     }
208     #else
209     char myIsTextUnicode(const void *b,int l) { return (char)IsTextUnicode((CONST LPVOID)b,l,NULL); };
210     #endif
211 #endif
212
213 #ifdef _XMLWINDOWS
214 // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET,
215     #ifdef _XMLUNICODE
216         wchar_t *myMultiByteToWideChar(const char *s,int l)
217         {
218             int i;
219             if (strictUTF8Parsing)  i=(int)MultiByteToWideChar(CP_UTF8,0             ,s,l,NULL,0);
220             else                    i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,l,NULL,0);
221             if (i<0) return NULL;
222             wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(XMLCHAR));
223             if (strictUTF8Parsing)  i=(int)MultiByteToWideChar(CP_UTF8,0             ,s,l,d,i);
224             else                    i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,l,d,i);
225             d[i]=0;
226             return d;
227         }
228     #else
229         char *myWideCharToMultiByte(const wchar_t *s,int l)
230         {
231             UINT codePage=CP_ACP; if (strictUTF8Parsing) codePage=CP_UTF8;
232             int i=(int)WideCharToMultiByte(codePage,  // code page
233                 0,                       // performance and mapping flags
234                 s,                       // wide-character string
235                 l,                       // number of chars in string
236                 NULL,                    // buffer for new string
237                 0,                       // size of buffer
238                 NULL,                    // default for unmappable chars
239                 NULL                     // set when default char used
240                 );
241             if (i<0) return NULL;
242             char *d=(char*)malloc(i+1);
243             WideCharToMultiByte(codePage,// code page
244                 0,                       // performance and mapping flags
245                 s,                       // wide-character string
246                 l,                       // number of chars in string
247                 d,                       // buffer for new string
248                 i,                       // size of buffer
249                 NULL,                    // default for unmappable chars
250                 NULL                     // set when default char used
251                 );
252             d[i]=0;
253             return d;
254         }
255     #endif
256     #ifdef __BORLANDC__
257     int _strnicmp(char *c1, char *c2, int l){ return strnicmp(c1,c2,l);}
258     #endif
259 #else
260 // for gcc and CC
261     #ifdef XML_NO_WIDE_CHAR
262         char *myWideCharToMultiByte(const wchar_t *s, int l) { return NULL; }
263     #else
264         char *myWideCharToMultiByte(const wchar_t *s, int l)
265         {
266             const wchar_t *ss=s;
267             int i=(int)wcsrtombs(NULL,&ss,0,NULL);
268             if (i<0) return NULL;
269             char *d=(char *)malloc(i+1);
270             wcsrtombs(d,&s,i,NULL);
271             d[i]=0;
272             return d;
273         }
274     #endif
275     #ifdef _XMLUNICODE
276         wchar_t *myMultiByteToWideChar(const char *s, int l)
277         {
278             const char *ss=s;
279             int i=(int)mbsrtowcs(NULL,&ss,0,NULL);
280             if (i<0) return NULL;
281             wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(wchar_t));
282             mbsrtowcs(d,&s,l,NULL);
283             d[i]=0;
284             return d;
285         }
286         int _tcslen(XMLCSTR c)   { return wcslen(c); }
287         #ifdef sun
288         // for CC
289            #include <widec.h>
290            int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncasecmp(c1,c2,l);}
291            int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return wscasecmp(c1,c2); }
292         #else
293         // for gcc
294            int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncasecmp(c1,c2,l);}
295            int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return wcscasecmp(c1,c2); }
296         #endif
297         XMLSTR _tcsstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
298         XMLSTR _tcscpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
299         FILE *_tfopen(XMLCSTR filename,XMLCSTR mode)
300         {
301             char *filenameAscii=myWideCharToMultiByte(filename,0);
302             FILE *f;
303             if (mode[0]==_T('r')) f=fopen(filenameAscii,"rb");
304             else                  f=fopen(filenameAscii,"wb");
305             free(filenameAscii);
306             return f;
307         }
308     #else
309         FILE *_tfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
310         int _tcslen(XMLCSTR c)   { return strlen(c); }
311         int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncasecmp(c1,c2,l);}
312         int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return strcasecmp(c1,c2); }
313         XMLSTR _tcsstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
314         XMLSTR _tcscpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
315     #endif
316     int _strnicmp(const char *c1,const char *c2, int l) { return strncasecmp(c1,c2,l);}
317 #endif
318
319 /////////////////////////////////////////////////////////////////////////
320 //      Here start the core implementation of the XMLParser library    //
321 /////////////////////////////////////////////////////////////////////////
322
323 // You should normally not change anything below this point.
324 // For your own information, I suggest that you read the openFileHelper below:
325 XMLNode XMLNode::openFileHelper(XMLCSTR filename, XMLCSTR tag)
326 {
327     // guess the value of the global parameter "strictUTF8Parsing"
328     // (the guess is based on the first 200 bytes of the file).
329     FILE *f=_tfopen(filename,_T("rb"));
330     if (f)
331     {
332         char bb[205];
333         int l=(int)fread(bb,1,200,f);
334         setGlobalOptions(guessUnicodeChars,guessUTF8ParsingParameterValue(bb,l),dropWhiteSpace);
335         fclose(f);
336     }
337
338     // parse the file
339     XMLResults pResults;
340     XMLNode xnode=XMLNode::parseFile(filename,tag,&pResults);
341
342     // display error message (if any)
343     if (pResults.error != eXMLErrorNone)
344     {
345         // create message
346         char message[2000],*s1=(char*)"",*s3=(char*)""; XMLCSTR s2=_T("");
347         if (pResults.error==eXMLErrorFirstTagNotFound) { s1=(char*)"First Tag should be '"; s2=tag; s3=(char*)"'.\n"; }
348         sprintf(message,
349 #ifdef _XMLUNICODE
350             "XML Parsing error inside file '%S'.\n%S\nAt line %i, column %i.\n%s%S%s"
351 #else
352             "XML Parsing error inside file '%s'.\n%s\nAt line %i, column %i.\n%s%s%s"
353 #endif
354             ,filename,XMLNode::getError(pResults.error),pResults.nLine,pResults.nColumn,s1,s2,s3);
355
356         // display message
357 #if defined(WIN32) && !defined(UNDER_CE) && !defined(_XMLPARSER_NO_MESSAGEBOX_)
358         MessageBoxA(NULL,message,"XML Parsing error",MB_OK|MB_ICONERROR|MB_TOPMOST);
359 #else
360         printf("%s",message);
361 #endif
362         exit(255);
363     }
364     return xnode;
365 }
366
367 #ifndef _XMLUNICODE
368 // If "strictUTF8Parsing=0" then we assume that all characters have the same length of 1 byte.
369 // If "strictUTF8Parsing=1" then the characters have different lengths (from 1 byte to 4 bytes).
370 // This table is used as lookup-table to know the length of a character (in byte) based on the
371 // content of the first byte of the character.
372 // (note: if you modify this, you must always have XML_utf8ByteTable[0]=0 ).
373 static const char XML_utf8ByteTable[256] =
374 {
375     //  0 1 2 3 4 5 6 7 8 9 a b c d e f
376     0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
377     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
378     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
379     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
380     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
381     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
382     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
383     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70End of ASCII range
384     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 0x80 to 0xc1 invalid
385     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
386     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
387     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
388     1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 0xc2 to 0xdf 2 byte
389     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
390     3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,// 0xe0 0xe0 to 0xef 3 byte
391     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
392 };
393 static const char XML_asciiByteTable[256] =
394 {
395     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,
396     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,
397     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,
398     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,
399     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,
400     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
401 };
402 static const char *XML_ByteTable=(const char *)XML_utf8ByteTable; // the default is "strictUTF8Parsing=1"
403 #endif
404
405 XMLError XMLNode::writeToFile(XMLCSTR filename, const char *encoding, char nFormat) const
406 {
407   //printf("EED XMLNode::writeToFile 01\n");
408     int i;
409     XMLSTR t=createXMLString(nFormat,&i);
410     FILE *f=_tfopen(filename,_T("wb"));
411     if (!f) return eXMLErrorCannotOpenWriteFile;
412 #ifdef _XMLUNICODE
413     unsigned char h[2]={ 0xFF, 0xFE };
414     if (!fwrite(h,2,1,f)) return eXMLErrorCannotWriteFile;
415     if (!isDeclaration())
416     {
417         if (!fwrite(_T("<?xml version=\"1.0\" encoding=\"utf-16\"?>\n"),sizeof(wchar_t)*40,1,f))
418             return eXMLErrorCannotWriteFile;
419     }
420 #else
421     if (!isDeclaration())
422     {
423         if ((!encoding)||(XML_ByteTable==XML_utf8ByteTable))
424         {
425             // header so that windows recognize the file as UTF-8:
426             unsigned char h[3]={0xEF,0xBB,0xBF};
427             if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
428             if (!fwrite("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",39,1,f)) return eXMLErrorCannotWriteFile;
429         }
430         else
431             if (fprintf(f,"<?xml version=\"1.0\" encoding=\"%s\"?>\n",encoding)<0) return eXMLErrorCannotWriteFile;
432     } else
433     {
434         if (XML_ByteTable==XML_utf8ByteTable) // test if strictUTF8Parsing==1"
435         {
436             unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
437         }
438     }
439 #endif
440     if (!fwrite(t,sizeof(XMLCHAR)*i,1,f)) return eXMLErrorCannotWriteFile;
441     //printf("EED XMLNode::writeToFile 02\n");
442     if (fclose(f)!=0) return eXMLErrorCannotWriteFile;
443     free(t);
444     return eXMLErrorNone;
445 }
446
447 // Duplicate a given string.
448 XMLSTR stringDup(XMLCSTR lpszData, int cbData)
449 {
450     if (lpszData==NULL) return NULL;
451
452     XMLSTR lpszNew;
453     if (cbData==0) cbData=(int)_tcslen(lpszData);
454     lpszNew = (XMLSTR)malloc((cbData+1) * sizeof(XMLCHAR));
455     if (lpszNew)
456     {
457         memcpy(lpszNew, lpszData, (cbData) * sizeof(XMLCHAR));
458         lpszNew[cbData] = (XMLCHAR)NULL;
459     }
460     return lpszNew;
461 }
462
463 XMLNode XMLNode::emptyXMLNode;
464 XMLClear XMLNode::emptyXMLClear={ NULL, NULL, NULL};
465 XMLAttribute XMLNode::emptyXMLAttribute={ NULL, NULL};
466
467 // Enumeration used to decipher what type a token is
468 typedef enum XMLTokenTypeTag
469 {
470     eTokenText = 0,
471     eTokenQuotedText,
472     eTokenTagStart,         /* "<"            */
473     eTokenTagEnd,           /* "</"           */
474     eTokenCloseTag,         /* ">"            */
475     eTokenEquals,           /* "="            */
476     eTokenDeclaration,      /* "<?"           */
477     eTokenShortHandClose,   /* "/>"           */
478     eTokenClear,
479     eTokenError
480 } XMLTokenType;
481
482 // Main structure used for parsing XML
483 typedef struct XML
484 {
485     XMLCSTR                lpXML;
486     XMLCSTR                lpszText;
487     int                    nIndex,nIndexMissigEndTag;
488     enum XMLError          error;
489     XMLCSTR                lpEndTag;
490     int                    cbEndTag;
491     XMLCSTR                lpNewElement;
492     int                    cbNewElement;
493     int                    nFirst;
494 } XML;
495
496 typedef struct
497 {
498     ALLXMLClearTag *pClr;
499     XMLCSTR     pStr;
500 } NextToken;
501
502 // Enumeration used when parsing attributes
503 typedef enum Attrib
504 {
505     eAttribName = 0,
506     eAttribEquals,
507     eAttribValue
508 } Attrib;
509
510 // Enumeration used when parsing elements to dictate whether we are currently
511 // inside a tag
512 typedef enum Status
513 {
514     eInsideTag = 0,
515     eOutsideTag
516 } Status;
517
518 // private (used while rendering):
519 XMLSTR toXMLString(XMLSTR dest,XMLCSTR source)
520 {
521     XMLSTR dd=dest;
522     XMLCHAR ch;
523     XMLCharacterEntity *entity;
524     while ((ch=*source))
525     {
526         entity=XMLEntities;
527         do
528         {
529             if (ch==entity->c) {_tcscpy(dest,entity->s); dest+=entity->l; source++; goto out_of_loop1; }
530             entity++;
531         } while(entity->s);
532 #ifdef _XMLUNICODE
533         *(dest++)=*(source++);
534 #else
535         switch(XML_ByteTable[(unsigned char)ch])
536         {
537         case 4: *(dest++)=*(source++);
538         case 3: *(dest++)=*(source++);
539         case 2: *(dest++)=*(source++);
540         case 1: *(dest++)=*(source++);
541         }
542 #endif
543 out_of_loop1:
544         ;
545     }
546     *dest=0;
547     return dd;
548 }
549
550 // private (used while rendering):
551 int lengthXMLString(XMLCSTR source)
552 {
553     int r=0;
554     XMLCharacterEntity *entity;
555     XMLCHAR ch;
556     while ((ch=*source))
557     {
558         entity=XMLEntities;
559         do
560         {
561             if (ch==entity->c) { r+=entity->l; source++; goto out_of_loop1; }
562             entity++;
563         } while(entity->s);
564 #ifdef _XMLUNICODE
565         r++; source++;
566 #else
567         ch=XML_ByteTable[(unsigned char)ch]; r+=ch; source+=ch;
568 #endif
569 out_of_loop1:
570         ;
571     }
572     return r;
573 }
574
575 XMLSTR toXMLString(XMLCSTR source)
576 {
577     XMLSTR dest=(XMLSTR)malloc((lengthXMLString(source)+1)*sizeof(XMLCHAR));
578     return toXMLString(dest,source);
579 }
580
581 XMLSTR toXMLStringFast(XMLSTR *dest,int *destSz, XMLCSTR source)
582 {
583     int l=lengthXMLString(source)+1;
584     if (l>*destSz) { *destSz=l; *dest=(XMLSTR)realloc(*dest,l*sizeof(XMLCHAR)); }
585     return toXMLString(*dest,source);
586 }
587
588 // private:
589 XMLSTR fromXMLString(XMLCSTR s, int lo, XML *pXML)
590 {
591     // This function is the opposite of the function "toXMLString". It decodes the escape
592     // sequences &amp;, &quot;, &apos;, &lt;, &gt; and replace them by the characters
593     // &,",',<,>. This function is used internally by the XML Parser. All the calls to
594     // the XML library will always gives you back "decoded" strings.
595     //
596     // in: string (s) and length (lo) of string
597     // out:  new allocated string converted from xml
598     if (!s) return NULL;
599
600     int ll=0,j;
601     XMLSTR d;
602     XMLCSTR ss=s;
603     XMLCharacterEntity *entity;
604     while ((lo>0)&&(*s))
605     {
606         if (*s==_T('&'))
607         {
608             if ((lo>2)&&(s[1]==_T('#')))
609             {
610                 s+=2; lo-=2;
611                 if ((*s==_T('X'))||(*s==_T('x'))) { s++; lo--; }
612                 while ((*s)&&(*s!=_T(';'))&&((lo--)>0)) s++;
613                 if (*s!=_T(';'))
614                 {
615                     pXML->error=eXMLErrorUnknownCharacterEntity;
616                     return NULL;
617                 }
618                 s++; lo--;
619             } else
620             {
621                 entity=XMLEntities;
622                 do
623                 {
624                     if ((lo>=entity->l)&&(_tcsnicmp(s,entity->s,entity->l)==0)) { s+=entity->l; lo-=entity->l; break; }
625                     entity++;
626                 } while(entity->s);
627                 if (!entity->s)
628                 {
629                     pXML->error=eXMLErrorUnknownCharacterEntity;
630                     return NULL;
631                 }
632             }
633         } else
634         {
635 #ifdef _XMLUNICODE
636             s++; lo--;
637 #else
638             j=XML_ByteTable[(unsigned char)*s]; s+=j; lo-=j; ll+=j-1;
639 #endif
640         }
641         ll++;
642     }
643
644     d=(XMLSTR)malloc((ll+1)*sizeof(XMLCHAR));
645     s=d;
646     while (ll-->0)
647     {
648         if (*ss==_T('&'))
649         {
650             if (ss[1]==_T('#'))
651             {
652                 ss+=2; j=0;
653                 if ((*ss==_T('X'))||(*ss==_T('x')))
654                 {
655                     ss++;
656                     while (*ss!=_T(';'))
657                     {
658                         if ((*ss>=_T('0'))&&(*ss<=_T('9'))) j=(j<<4)+*ss-_T('0');
659                         else if ((*ss>=_T('A'))&&(*ss<=_T('F'))) j=(j<<4)+*ss-_T('A')+10;
660                         else if ((*ss>=_T('a'))&&(*ss<=_T('f'))) j=(j<<4)+*ss-_T('a')+10;
661                         else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
662                         ss++;
663                     }
664                 } else
665                 {
666                     while (*ss!=_T(';'))
667                     {
668                         if ((*ss>=_T('0'))&&(*ss<=_T('9'))) j=(j*10)+*ss-_T('0');
669                         else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
670                         ss++;
671                     }
672                 }
673                 (*d++)=(XMLCHAR)j; ss++;
674             } else
675             {
676                 entity=XMLEntities;
677                 do
678                 {
679                     if (_tcsnicmp(ss,entity->s,entity->l)==0) { *(d++)=entity->c; ss+=entity->l; break; }
680                     entity++;
681                 } while(entity->s);
682             }
683         } else
684         {
685 #ifdef _XMLUNICODE
686             *(d++)=*(ss++);
687 #else
688             switch(XML_ByteTable[(unsigned char)*ss])
689             {
690             case 4: *(d++)=*(ss++); ll--;
691             case 3: *(d++)=*(ss++); ll--;
692             case 2: *(d++)=*(ss++); ll--;
693             case 1: *(d++)=*(ss++);
694             }
695 #endif
696         }
697     }
698     *d=0;
699     return (XMLSTR)s;
700 }
701
702 #define XML_isSPACECHAR(ch) ((ch==_T('\n'))||(ch==_T(' '))||(ch== _T('\t'))||(ch==_T('\r')))
703
704 // private:
705 char myTagCompare(XMLCSTR cclose, XMLCSTR copen)
706 // !!!! WARNING strange convention&:
707 // return 0 if equals
708 // return 1 if different
709 {
710     if (!cclose) return 1;
711     int l=(int)_tcslen(cclose);
712     if (_tcsnicmp(cclose, copen, l)!=0) return 1;
713     const XMLCHAR c=copen[l];
714     if (XML_isSPACECHAR(c)||
715         (c==_T('/' ))||
716         (c==_T('<' ))||
717         (c==_T('>' ))||
718         (c==_T('=' ))) return 0;
719     return 1;
720 }
721
722 // Obtain the next character from the string.
723 static inline XMLCHAR getNextChar(XML *pXML)
724 {
725     XMLCHAR ch = pXML->lpXML[pXML->nIndex];
726 #ifdef _XMLUNICODE
727     if (ch!=0) pXML->nIndex++;
728 #else
729     pXML->nIndex+=XML_ByteTable[(unsigned char)ch];
730 #endif
731     return ch;
732 }
733
734 // Find the next token in a string.
735 // pcbToken contains the number of characters that have been read.
736 static NextToken GetNextToken(XML *pXML, int *pcbToken, enum XMLTokenTypeTag *pType)
737 {
738     NextToken        result;
739     XMLCHAR            ch;
740     XMLCHAR            chTemp;
741     int              indexStart,nFoundMatch,nIsText=FALSE;
742     result.pClr=NULL; // prevent warning
743
744     // Find next non-white space character
745     do { indexStart=pXML->nIndex; ch=getNextChar(pXML); } while XML_isSPACECHAR(ch);
746
747     if (ch)
748     {
749         // Cache the current string pointer
750         result.pStr = &pXML->lpXML[indexStart];
751
752         // First check whether the token is in the clear tag list (meaning it
753         // does not need formatting).
754         ALLXMLClearTag *ctag=XMLClearTags;
755         do
756         {
757             if (_tcsnicmp(ctag->lpszOpen, result.pStr, ctag->openTagLen)==0)
758             {
759                 result.pClr=ctag;
760                 pXML->nIndex+=ctag->openTagLen-1;
761                 *pType=eTokenClear;
762                 return result;
763             }
764             ctag++;
765         } while(ctag->lpszOpen);
766
767         // If we didn't find a clear tag then check for standard tokens
768         switch(ch)
769         {
770         // Check for quotes
771         case _T('\''):
772         case _T('\"'):
773             // Type of token
774             *pType = eTokenQuotedText;
775             chTemp = ch;
776
777             // Set the size
778             nFoundMatch = FALSE;
779
780             // Search through the string to find a matching quote
781             while((ch = getNextChar(pXML)))
782             {
783                 if (ch==chTemp) { nFoundMatch = TRUE; break; }
784                 if (ch==_T('<')) break;
785             }
786
787             // If we failed to find a matching quote
788             if (nFoundMatch == FALSE)
789             {
790                 pXML->nIndex=indexStart+1;
791                 nIsText=TRUE;
792                 break;
793             }
794
795 //  4.02.2002
796 //            if (FindNonWhiteSpace(pXML)) pXML->nIndex--;
797
798             break;
799
800         // Equals (used with attribute values)
801         case _T('='):
802             *pType = eTokenEquals;
803             break;
804
805         // Close tag
806         case _T('>'):
807             *pType = eTokenCloseTag;
808             break;
809
810         // Check for tag start and tag end
811         case _T('<'):
812
813             // Peek at the next character to see if we have an end tag '</',
814             // or an xml declaration '<?'
815             chTemp = pXML->lpXML[pXML->nIndex];
816
817             // If we have a tag end...
818             if (chTemp == _T('/'))
819             {
820                 // Set the type and ensure we point at the next character
821                 getNextChar(pXML);
822                 *pType = eTokenTagEnd;
823             }
824
825             // If we have an XML declaration tag
826             else if (chTemp == _T('?'))
827             {
828
829                 // Set the type and ensure we point at the next character
830                 getNextChar(pXML);
831                 *pType = eTokenDeclaration;
832             }
833
834             // Otherwise we must have a start tag
835             else
836             {
837                 *pType = eTokenTagStart;
838             }
839             break;
840
841         // Check to see if we have a short hand type end tag ('/>').
842         case _T('/'):
843
844             // Peek at the next character to see if we have a short end tag '/>'
845             chTemp = pXML->lpXML[pXML->nIndex];
846
847             // If we have a short hand end tag...
848             if (chTemp == _T('>'))
849             {
850                 // Set the type and ensure we point at the next character
851                 getNextChar(pXML);
852                 *pType = eTokenShortHandClose;
853                 break;
854             }
855
856             // If we haven't found a short hand closing tag then drop into the
857             // text process
858
859         // Other characters
860         default:
861             nIsText = TRUE;
862         }
863
864         // If this is a TEXT node
865         if (nIsText)
866         {
867             // Indicate we are dealing with text
868             *pType = eTokenText;
869             while((ch = getNextChar(pXML)))
870             {
871                 if XML_isSPACECHAR(ch)
872                 {
873                     indexStart++; break;
874
875                 } else if (ch==_T('/'))
876                 {
877                     // If we find a slash then this maybe text or a short hand end tag
878                     // Peek at the next character to see it we have short hand end tag
879                     ch=pXML->lpXML[pXML->nIndex];
880                     // If we found a short hand end tag then we need to exit the loop
881                     if (ch==_T('>')) { pXML->nIndex--; break; }
882
883                 } else if ((ch==_T('<'))||(ch==_T('>'))||(ch==_T('=')))
884                 {
885                     pXML->nIndex--; break;
886                 }
887             }
888         }
889         *pcbToken = pXML->nIndex-indexStart;
890     } else
891     {
892         // If we failed to obtain a valid character
893         *pcbToken = 0;
894         *pType = eTokenError;
895         result.pStr=NULL;
896     }
897
898     return result;
899 }
900
901 XMLCSTR XMLNode::updateName_WOSD(XMLCSTR lpszName)
902 {
903     if (d->lpszName&&(lpszName!=d->lpszName)) free((void*)d->lpszName);
904     d->lpszName=lpszName;
905     return lpszName;
906 }
907
908 // private:
909 XMLNode::XMLNode(struct XMLNodeDataTag *p){ d=p; (p->ref_count)++; }
910 XMLNode::XMLNode(XMLNodeData *pParent, XMLCSTR lpszName, char isDeclaration)
911 {
912     d=(XMLNodeData*)malloc(sizeof(XMLNodeData));
913     d->ref_count=1;
914
915     d->lpszName=NULL;
916     d->nChild= 0;
917     d->nText = 0;
918     d->nClear = 0;
919     d->nAttribute = 0;
920
921     d->isDeclaration = isDeclaration;
922
923     d->pParent = pParent;
924     d->pChild= NULL;
925     d->pText= NULL;
926     d->pClear= NULL;
927     d->pAttribute= NULL;
928     d->pOrder= NULL;
929
930     updateName_WOSD(lpszName);
931 }
932
933 XMLNode XMLNode::createXMLTopNode_WOSD(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,lpszName,isDeclaration); }
934 XMLNode XMLNode::createXMLTopNode(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,stringDup(lpszName),isDeclaration); }
935
936 #define MEMORYINCREASE 50
937
938 static inline void *myRealloc(void *p, int newsize, int memInc, int sizeofElem)
939 {
940     if (p==NULL) { if (memInc) return malloc(memInc*sizeofElem); return malloc(sizeofElem); }
941     if ((memInc==0)||((newsize%memInc)==0)) p=realloc(p,(newsize+memInc)*sizeofElem);
942 //    if (!p)
943 //    {
944 //        printf("XMLParser Error: Not enough memory! Aborting...\n"); exit(220);
945 //    }
946     return p;
947 }
948
949 // private:
950 int XMLNode::findPosition(XMLNodeData *d, int index, XMLElementType xtype)
951 {
952     if (index<0) return -1;
953     int i=0,j=(int)((index<<2)+xtype),*o=d->pOrder; while (o[i]!=j) i++; return i;
954 }
955
956 // private:
957 // update "order" information when deleting a content of a XMLNode
958 int XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index)
959 {
960     int n=d->nChild+d->nText+d->nClear, *o=d->pOrder,i=findPosition(d,index,t);
961     memmove(o+i, o+i+1, (n-i)*sizeof(int));
962     for (;i<n;i++)
963         if ((o[i]&3)==(int)t) o[i]-=4;
964     // We should normally do:
965     // d->pOrder=(int)realloc(d->pOrder,n*sizeof(int));
966     // but we skip reallocation because it's too time consuming.
967     // Anyway, at the end, it will be free'd completely at once.
968     return i;
969 }
970
971 void *XMLNode::addToOrder(int memoryIncrease,int *_pos, int nc, void *p, int size, XMLElementType xtype)
972 {
973     //  in: *_pos is the position inside d->pOrder ("-1" means "EndOf")
974     // out: *_pos is the index inside p
975     p=myRealloc(p,(nc+1),memoryIncrease,size);
976     int n=d->nChild+d->nText+d->nClear;
977     d->pOrder=(int*)myRealloc(d->pOrder,n+1,memoryIncrease*3,sizeof(int));
978     int pos=*_pos,*o=d->pOrder;
979
980     if ((pos<0)||(pos>=n)) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
981
982     int i=pos;
983     memmove(o+i+1, o+i, (n-i)*sizeof(int));
984
985     while ((pos<n)&&((o[pos]&3)!=(int)xtype)) pos++;
986     if (pos==n) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
987
988     o[i]=o[pos];
989     for (i=pos+1;i<=n;i++) if ((o[i]&3)==(int)xtype) o[i]+=4;
990
991     *_pos=pos=o[pos]>>2;
992     memmove(((char*)p)+(pos+1)*size,((char*)p)+pos*size,(nc-pos)*size);
993
994     return p;
995 }
996
997 // Add a child node to the given element.
998 XMLNode XMLNode::addChild_priv(int memoryIncrease, XMLCSTR lpszName, char isDeclaration, int pos)
999 {
1000     if (!lpszName) return emptyXMLNode;
1001     d->pChild=(XMLNode*)addToOrder(memoryIncrease,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
1002     d->pChild[pos].d=NULL;
1003     d->pChild[pos]=XMLNode(d,lpszName,isDeclaration);
1004     d->nChild++;
1005     return d->pChild[pos];
1006 }
1007
1008 // Add an attribute to an element.
1009 XMLAttribute *XMLNode::addAttribute_priv(int memoryIncrease,XMLCSTR lpszName, XMLCSTR lpszValuev)
1010 {
1011     if (!lpszName) return &emptyXMLAttribute;
1012     int nc=d->nAttribute;
1013     d->pAttribute=(XMLAttribute*)myRealloc(d->pAttribute,(nc+1),memoryIncrease,sizeof(XMLAttribute));
1014     XMLAttribute *pAttr=d->pAttribute+nc;
1015     pAttr->lpszName = lpszName;
1016     pAttr->lpszValue = lpszValuev;
1017     d->nAttribute++;
1018     return pAttr;
1019 }
1020
1021 // Add text to the element.
1022 XMLCSTR XMLNode::addText_priv(int memoryIncrease, XMLCSTR lpszValue, int pos)
1023 {
1024     if (!lpszValue) return NULL;
1025     d->pText=(XMLCSTR*)addToOrder(memoryIncrease,&pos,d->nText,d->pText,sizeof(XMLSTR),eNodeText);
1026     d->pText[pos]=lpszValue;
1027     d->nText++;
1028     return lpszValue;
1029 }
1030
1031 // Add clear (unformatted) text to the element.
1032 XMLClear *XMLNode::addClear_priv(int memoryIncrease, XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
1033 {
1034     if (!lpszValue) return &emptyXMLClear;
1035     d->pClear=(XMLClear *)addToOrder(memoryIncrease,&pos,d->nClear,d->pClear,sizeof(XMLClear),eNodeClear);
1036     XMLClear *pNewClear=d->pClear+pos;
1037     pNewClear->lpszValue = lpszValue;
1038     if (!lpszOpen) lpszOpen=getClearTagTable()->lpszOpen;
1039     if (!lpszClose) lpszOpen=getClearTagTable()->lpszClose;
1040     pNewClear->lpszOpenTag = lpszOpen;
1041     pNewClear->lpszCloseTag = lpszClose;
1042     d->nClear++;
1043     return pNewClear;
1044 }
1045
1046 // private:
1047 // Parse a clear (unformatted) type node.
1048 char XMLNode::parseClearTag(void *px, ALLXMLClearTag *pClear)
1049 {
1050     XML *pXML=(XML *)px;
1051     int cbTemp=0;
1052     XMLCSTR lpszTemp=NULL;
1053     XMLCSTR lpXML=&pXML->lpXML[pXML->nIndex];
1054     static XMLCSTR docTypeEnd=_T("]>");
1055
1056     // Find the closing tag
1057     // Seems the <!DOCTYPE need a better treatment so lets handle it
1058     if (pClear->lpszOpen==XMLClearTags[1].lpszOpen)
1059     {
1060         XMLCSTR pCh=lpXML;
1061         while (*pCh)
1062         {
1063             if (*pCh==_T('<')) { pClear->lpszClose=docTypeEnd; lpszTemp=_tcsstr(lpXML,docTypeEnd); break; }
1064             else if (*pCh==_T('>')) { lpszTemp=pCh; break; }
1065 #ifdef _XMLUNICODE
1066             pCh++;
1067 #else
1068             pCh+=XML_ByteTable[(unsigned char)(*pCh)];
1069 #endif
1070         }
1071     } else lpszTemp=_tcsstr(lpXML, pClear->lpszClose);
1072
1073     if (lpszTemp)
1074     {
1075         // Cache the size and increment the index
1076         cbTemp = (int)(lpszTemp - lpXML);
1077
1078         pXML->nIndex += cbTemp+(int)_tcslen(pClear->lpszClose);
1079
1080         // Add the clear node to the current element
1081         addClear_priv(MEMORYINCREASE,stringDup(lpXML,cbTemp), pClear->lpszOpen, pClear->lpszClose,-1);
1082         return 0;
1083     }
1084
1085     // If we failed to find the end tag
1086     pXML->error = eXMLErrorUnmatchedEndClearTag;
1087     return 1;
1088 }
1089
1090 void XMLNode::exactMemory(XMLNodeData *d)
1091 {
1092     if (d->pOrder)     d->pOrder=(int*)realloc(d->pOrder,(d->nChild+d->nText+d->nClear)*sizeof(int));
1093     if (d->pChild)     d->pChild=(XMLNode*)realloc(d->pChild,d->nChild*sizeof(XMLNode));
1094     if (d->pAttribute) d->pAttribute=(XMLAttribute*)realloc(d->pAttribute,d->nAttribute*sizeof(XMLAttribute));
1095     if (d->pText)      d->pText=(XMLCSTR*)realloc(d->pText,d->nText*sizeof(XMLSTR));
1096     if (d->pClear)     d->pClear=(XMLClear *)realloc(d->pClear,d->nClear*sizeof(XMLClear));
1097 }
1098
1099 char XMLNode::maybeAddTxT(void *pa, XMLCSTR tokenPStr)
1100 {
1101     XML *pXML=(XML *)pa;
1102     XMLCSTR lpszText=pXML->lpszText;
1103     if (!lpszText) return 0;
1104     if (dropWhiteSpace) while (XML_isSPACECHAR(*lpszText)&&(lpszText!=tokenPStr)) lpszText++;
1105     int cbText = (int)(tokenPStr - lpszText);
1106     if (!cbText) { pXML->lpszText=NULL; return 0; }
1107     if (dropWhiteSpace) { cbText--; while ((cbText)&&XML_isSPACECHAR(lpszText[cbText])) cbText--; cbText++; }
1108     if (!cbText) { pXML->lpszText=NULL; return 0; }
1109     lpszText=fromXMLString(lpszText,cbText,pXML);
1110     if (!lpszText) return 1;
1111     addText_priv(MEMORYINCREASE,lpszText,-1);
1112     pXML->lpszText=NULL;
1113     return 0;
1114 }
1115 // private:
1116 // Recursively parse an XML element.
1117 int XMLNode::ParseXMLElement(void *pa)
1118 {
1119     XML *pXML=(XML *)pa;
1120     int cbToken;
1121     enum XMLTokenTypeTag type;
1122     NextToken token;
1123     XMLCSTR lpszTemp=NULL;
1124     int cbTemp=0;
1125     char nDeclaration;
1126     XMLNode pNew;
1127     enum Status status; // inside or outside a tag
1128     enum Attrib attrib = eAttribName;
1129
1130     assert(pXML);
1131
1132     // If this is the first call to the function
1133     if (pXML->nFirst)
1134     {
1135         // Assume we are outside of a tag definition
1136         pXML->nFirst = FALSE;
1137         status = eOutsideTag;
1138     } else
1139     {
1140         // If this is not the first call then we should only be called when inside a tag.
1141         status = eInsideTag;
1142     }
1143
1144     // Iterate through the tokens in the document
1145     for(;;)
1146     {
1147         // Obtain the next token
1148         token = GetNextToken(pXML, &cbToken, &type);
1149
1150         if (type != eTokenError)
1151         {
1152             // Check the current status
1153             switch(status)
1154             {
1155
1156             // If we are outside of a tag definition
1157             case eOutsideTag:
1158
1159                 // Check what type of token we obtained
1160                 switch(type)
1161                 {
1162                 // If we have found text or quoted text
1163                 case eTokenText:
1164                 case eTokenCloseTag:          /* '>'         */
1165                 case eTokenShortHandClose:    /* '/>'        */
1166                 case eTokenQuotedText:
1167                 case eTokenEquals:
1168                     break;
1169
1170                 // If we found a start tag '<' and declarations '<?'
1171                 case eTokenTagStart:
1172                 case eTokenDeclaration:
1173
1174                     // Cache whether this new element is a declaration or not
1175                     nDeclaration = (type == eTokenDeclaration);
1176
1177                     // If we have node text then add this to the element
1178                     if (maybeAddTxT(pXML,token.pStr)) return FALSE;
1179
1180                     // Find the name of the tag
1181                     token = GetNextToken(pXML, &cbToken, &type);
1182
1183                     // Return an error if we couldn't obtain the next token or
1184                     // it wasnt text
1185                     if (type != eTokenText)
1186                     {
1187                         pXML->error = eXMLErrorMissingTagName;
1188                         return FALSE;
1189                     }
1190
1191                     // If we found a new element which is the same as this
1192                     // element then we need to pass this back to the caller..
1193
1194 #ifdef APPROXIMATE_PARSING
1195                     if (d->lpszName &&
1196                         myTagCompare(d->lpszName, token.pStr) == 0)
1197                     {
1198                         // Indicate to the caller that it needs to create a
1199                         // new element.
1200                         pXML->lpNewElement = token.pStr;
1201                         pXML->cbNewElement = cbToken;
1202                         return TRUE;
1203                     } else
1204 #endif
1205                     {
1206                         // If the name of the new element differs from the name of
1207                         // the current element we need to add the new element to
1208                         // the current one and recurse
1209                         pNew = addChild_priv(MEMORYINCREASE,stringDup(token.pStr,cbToken), nDeclaration,-1);
1210
1211                         while (!pNew.isEmpty())
1212                         {
1213                             // Callself to process the new node.  If we return
1214                             // FALSE this means we dont have any more
1215                             // processing to do...
1216
1217                             if (!pNew.ParseXMLElement(pXML)) return FALSE;
1218                             else
1219                             {
1220                                 // If the call to recurse this function
1221                                 // evented in a end tag specified in XML then
1222                                 // we need to unwind the calls to this
1223                                 // function until we find the appropriate node
1224                                 // (the element name and end tag name must
1225                                 // match)
1226                                 if (pXML->cbEndTag)
1227                                 {
1228                                     // If we are back at the root node then we
1229                                     // have an unmatched end tag
1230                                     if (!d->lpszName)
1231                                     {
1232                                         pXML->error=eXMLErrorUnmatchedEndTag;
1233                                         return FALSE;
1234                                     }
1235
1236                                     // If the end tag matches the name of this
1237                                     // element then we only need to unwind
1238                                     // once more...
1239
1240                                     if (myTagCompare(d->lpszName, pXML->lpEndTag)==0)
1241                                     {
1242                                         pXML->cbEndTag = 0;
1243                                     }
1244
1245                                     return TRUE;
1246                                 } else
1247                                     if (pXML->cbNewElement)
1248                                     {
1249                                         // If the call indicated a new element is to
1250                                         // be created on THIS element.
1251
1252                                         // If the name of this element matches the
1253                                         // name of the element we need to create
1254                                         // then we need to return to the caller
1255                                         // and let it process the element.
1256
1257                                         if (myTagCompare(d->lpszName, pXML->lpNewElement)==0)
1258                                         {
1259                                             return TRUE;
1260                                         }
1261
1262                                         // Add the new element and recurse
1263                                         pNew = addChild_priv(MEMORYINCREASE,stringDup(pXML->lpNewElement,pXML->cbNewElement),0,-1);
1264                                         pXML->cbNewElement = 0;
1265                                     }
1266                                     else
1267                                     {
1268                                         // If we didn't have a new element to create
1269                                         pNew = emptyXMLNode;
1270
1271                                     }
1272                             }
1273                         }
1274                     }
1275                     break;
1276
1277                 // If we found an end tag
1278                 case eTokenTagEnd:
1279
1280                     // If we have node text then add this to the element
1281                     if (maybeAddTxT(pXML,token.pStr)) return FALSE;
1282
1283                     // Find the name of the end tag
1284                     token = GetNextToken(pXML, &cbTemp, &type);
1285
1286                     // The end tag should be text
1287                     if (type != eTokenText)
1288                     {
1289                         pXML->error = eXMLErrorMissingEndTagName;
1290                         return FALSE;
1291                     }
1292                     lpszTemp = token.pStr;
1293
1294                     // After the end tag we should find a closing tag
1295                     token = GetNextToken(pXML, &cbToken, &type);
1296                     if (type != eTokenCloseTag)
1297                     {
1298                         pXML->error = eXMLErrorMissingEndTagName;
1299                         return FALSE;
1300                     }
1301                     pXML->lpszText=pXML->lpXML+pXML->nIndex;
1302
1303                     // We need to return to the previous caller.  If the name
1304                     // of the tag cannot be found we need to keep returning to
1305                     // caller until we find a match
1306                     if (myTagCompare(d->lpszName, lpszTemp) != 0)
1307 #ifdef STRICT_PARSING
1308                     {
1309                         pXML->error=eXMLErrorUnmatchedEndTag;
1310                         pXML->nIndexMissigEndTag=pXML->nIndex;
1311                         return FALSE;
1312                     }
1313 #else
1314                     {
1315                         pXML->error=eXMLErrorMissingEndTag;
1316                         pXML->nIndexMissigEndTag=pXML->nIndex;
1317                         pXML->lpEndTag = lpszTemp;
1318                         pXML->cbEndTag = cbTemp;
1319                     }
1320 #endif
1321
1322                     // Return to the caller
1323                     exactMemory(d);
1324                     return TRUE;
1325
1326                 // If we found a clear (unformatted) token
1327                 case eTokenClear:
1328                     // If we have node text then add this to the element
1329                     if (maybeAddTxT(pXML,token.pStr)) return FALSE;
1330                     if (parseClearTag(pXML, token.pClr)) return FALSE;
1331                     pXML->lpszText=pXML->lpXML+pXML->nIndex;
1332                     break;
1333
1334                 default:
1335                     break;
1336                 }
1337                 break;
1338
1339             // If we are inside a tag definition we need to search for attributes
1340             case eInsideTag:
1341
1342                 // Check what part of the attribute (name, equals, value) we
1343                 // are looking for.
1344                 switch(attrib)
1345                 {
1346                 // If we are looking for a new attribute
1347                 case eAttribName:
1348
1349                     // Check what the current token type is
1350                     switch(type)
1351                     {
1352                     // If the current type is text...
1353                     // Eg.  'attribute'
1354                     case eTokenText:
1355                         // Cache the token then indicate that we are next to
1356                         // look for the equals
1357                         lpszTemp = token.pStr;
1358                         cbTemp = cbToken;
1359                         attrib = eAttribEquals;
1360                         break;
1361
1362                     // If we found a closing tag...
1363                     // Eg.  '>'
1364                     case eTokenCloseTag:
1365                         // We are now outside the tag
1366                         status = eOutsideTag;
1367                         pXML->lpszText=pXML->lpXML+pXML->nIndex;
1368                         break;
1369
1370                     // If we found a short hand '/>' closing tag then we can
1371                     // return to the caller
1372                     case eTokenShortHandClose:
1373                         exactMemory(d);
1374                         pXML->lpszText=pXML->lpXML+pXML->nIndex;
1375                         return TRUE;
1376
1377                     // Errors...
1378                     case eTokenQuotedText:    /* '"SomeText"'   */
1379                     case eTokenTagStart:      /* '<'            */
1380                     case eTokenTagEnd:        /* '</'           */
1381                     case eTokenEquals:        /* '='            */
1382                     case eTokenDeclaration:   /* '<?'           */
1383                     case eTokenClear:
1384                         pXML->error = eXMLErrorUnexpectedToken;
1385                         return FALSE;
1386                     default: break;
1387                     }
1388                     break;
1389
1390                 // If we are looking for an equals
1391                 case eAttribEquals:
1392                     // Check what the current token type is
1393                     switch(type)
1394                     {
1395                     // If the current type is text...
1396                     // Eg.  'Attribute AnotherAttribute'
1397                     case eTokenText:
1398                         // Add the unvalued attribute to the list
1399                         addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
1400                         // Cache the token then indicate.  We are next to
1401                         // look for the equals attribute
1402                         lpszTemp = token.pStr;
1403                         cbTemp = cbToken;
1404                         break;
1405
1406                     // If we found a closing tag 'Attribute >' or a short hand
1407                     // closing tag 'Attribute />'
1408                     case eTokenShortHandClose:
1409                     case eTokenCloseTag:
1410                         // If we are a declaration element '<?' then we need
1411                         // to remove extra closing '?' if it exists
1412                         pXML->lpszText=pXML->lpXML+pXML->nIndex;
1413
1414                         if (d->isDeclaration &&
1415                             (lpszTemp[cbTemp-1]) == _T('?'))
1416                         {
1417                             cbTemp--;
1418                         }
1419
1420                         if (cbTemp)
1421                         {
1422                             // Add the unvalued attribute to the list
1423                             addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
1424                         }
1425
1426                         // If this is the end of the tag then return to the caller
1427                         if (type == eTokenShortHandClose)
1428                         {
1429                             exactMemory(d);
1430                             return TRUE;
1431                         }
1432
1433                         // We are now outside the tag
1434                         status = eOutsideTag;
1435                         break;
1436
1437                     // If we found the equals token...
1438                     // Eg.  'Attribute ='
1439                     case eTokenEquals:
1440                         // Indicate that we next need to search for the value
1441                         // for the attribute
1442                         attrib = eAttribValue;
1443                         break;
1444
1445                     // Errors...
1446                     case eTokenQuotedText:    /* 'Attribute "InvalidAttr"'*/
1447                     case eTokenTagStart:      /* 'Attribute <'            */
1448                     case eTokenTagEnd:        /* 'Attribute </'           */
1449                     case eTokenDeclaration:   /* 'Attribute <?'           */
1450                     case eTokenClear:
1451                         pXML->error = eXMLErrorUnexpectedToken;
1452                         return FALSE;
1453                     default: break;
1454                     }
1455                     break;
1456
1457                 // If we are looking for an attribute value
1458                 case eAttribValue:
1459                     // Check what the current token type is
1460                     switch(type)
1461                     {
1462                     // If the current type is text or quoted text...
1463                     // Eg.  'Attribute = "Value"' or 'Attribute = Value' or
1464                     // 'Attribute = 'Value''.
1465                     case eTokenText:
1466                     case eTokenQuotedText:
1467                         // If we are a declaration element '<?' then we need
1468                         // to remove extra closing '?' if it exists
1469                         if (d->isDeclaration &&
1470                             (token.pStr[cbToken-1]) == _T('?'))
1471                         {
1472                             cbToken--;
1473                         }
1474
1475                         if (cbTemp)
1476                         {
1477                             // Add the valued attribute to the list
1478                             if (type==eTokenQuotedText) { token.pStr++; cbToken-=2; }
1479                             XMLCSTR attrVal=token.pStr;
1480                             if (attrVal)
1481                             {
1482                                 attrVal=fromXMLString(attrVal,cbToken,pXML);
1483                                 if (!attrVal) return FALSE;
1484                             }
1485                             addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp),attrVal);
1486                         }
1487
1488                         // Indicate we are searching for a new attribute
1489                         attrib = eAttribName;
1490                         break;
1491
1492                     // Errors...
1493                     case eTokenTagStart:        /* 'Attr = <'          */
1494                     case eTokenTagEnd:          /* 'Attr = </'         */
1495                     case eTokenCloseTag:        /* 'Attr = >'          */
1496                     case eTokenShortHandClose:  /* "Attr = />"         */
1497                     case eTokenEquals:          /* 'Attr = ='          */
1498                     case eTokenDeclaration:     /* 'Attr = <?'         */
1499                     case eTokenClear:
1500                         pXML->error = eXMLErrorUnexpectedToken;
1501                         return FALSE;
1502                         break;
1503                     default: break;
1504                     }
1505                 }
1506             }
1507         }
1508         // If we failed to obtain the next token
1509         else
1510         {
1511             if ((!d->isDeclaration)&&(d->pParent))
1512             {
1513 #ifdef STRICT_PARSING
1514                 pXML->error=eXMLErrorUnmatchedEndTag;
1515 #else
1516                 pXML->error=eXMLErrorMissingEndTag;
1517 #endif
1518                 pXML->nIndexMissigEndTag=pXML->nIndex;
1519             }
1520             return FALSE;
1521         }
1522     }
1523 }
1524
1525 // Count the number of lines and columns in an XML string.
1526 static void CountLinesAndColumns(XMLCSTR lpXML, int nUpto, XMLResults *pResults)
1527 {
1528     XMLCHAR ch;
1529     assert(lpXML);
1530     assert(pResults);
1531
1532     struct XML xml={ lpXML,lpXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
1533
1534     pResults->nLine = 1;
1535     pResults->nColumn = 1;
1536     while (xml.nIndex<nUpto)
1537     {
1538         ch = getNextChar(&xml);
1539         if (ch != _T('\n')) pResults->nColumn++;
1540         else
1541         {
1542             pResults->nLine++;
1543             pResults->nColumn=1;
1544         }
1545     }
1546 }
1547
1548 // Parse XML and return the root element.
1549 XMLNode XMLNode::parseString(XMLCSTR lpszXML, XMLCSTR tag, XMLResults *pResults)
1550 {
1551     if (!lpszXML)
1552     {
1553         if (pResults)
1554         {
1555             pResults->error=eXMLErrorNoElements;
1556             pResults->nLine=0;
1557             pResults->nColumn=0;
1558         }
1559         return emptyXMLNode;
1560     }
1561
1562     XMLNode xnode(NULL,NULL,FALSE);
1563     struct XML xml={ lpszXML, lpszXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
1564
1565     // Create header element
1566     xnode.ParseXMLElement(&xml);
1567     enum XMLError error = xml.error;
1568     if ((xnode.nChildNode()==1)&&(xnode.nElement()==1)) xnode=xnode.getChildNode(); // skip the empty node
1569
1570     // If no error occurred
1571     if ((error==eXMLErrorNone)||(error==eXMLErrorMissingEndTag))
1572     {
1573         XMLCSTR name=xnode.getName();
1574         if (tag&&_tcslen(tag)&&((!name)||(_tcsicmp(xnode.getName(),tag))))
1575         {
1576             XMLNode nodeTmp;
1577             int i=0;
1578             while (i<xnode.nChildNode())
1579             {
1580                 nodeTmp=xnode.getChildNode(i);
1581                 if (_tcsicmp(nodeTmp.getName(),tag)==0) break;
1582                 if (nodeTmp.isDeclaration()) { xnode=nodeTmp; i=0; } else i++;
1583             }
1584             if (i>=xnode.nChildNode())
1585             {
1586                 if (pResults)
1587                 {
1588                     pResults->error=eXMLErrorFirstTagNotFound;
1589                     pResults->nLine=0;
1590                     pResults->nColumn=0;
1591                 }
1592                 return emptyXMLNode;
1593             }
1594             xnode=nodeTmp;
1595         }
1596     } else
1597     {
1598         // Cleanup: this will destroy all the nodes
1599         xnode = emptyXMLNode;
1600     }
1601
1602
1603     // If we have been given somewhere to place results
1604     if (pResults)
1605     {
1606         pResults->error = error;
1607
1608         // If we have an error
1609         if (error!=eXMLErrorNone)
1610         {
1611             if (error==eXMLErrorMissingEndTag) xml.nIndex=xml.nIndexMissigEndTag;
1612             // Find which line and column it starts on.
1613             CountLinesAndColumns(xml.lpXML, xml.nIndex, pResults);
1614         }
1615     }
1616     return xnode;
1617 }
1618
1619 XMLNode XMLNode::parseFile(XMLCSTR filename, XMLCSTR tag, XMLResults *pResults)
1620 {
1621     if (pResults) { pResults->nLine=0; pResults->nColumn=0; }
1622     FILE *f=_tfopen(filename,_T("rb"));
1623     if (f==NULL) { if (pResults) pResults->error=eXMLErrorFileNotFound; return emptyXMLNode; }
1624     fseek(f,0,SEEK_END);
1625     int l=ftell(f),headerSz=0;
1626     if (!l) { if (pResults) pResults->error=eXMLErrorEmpty; return emptyXMLNode; }
1627     fseek(f,0,SEEK_SET);
1628     unsigned char *buf=(unsigned char*)malloc(l+1);
1629     fread(buf,l,1,f);
1630     fclose(f);
1631     buf[l]=0;
1632 #ifdef _XMLUNICODE
1633     if (guessUnicodeChars)
1634     {
1635         if (!myIsTextUnicode(buf,l))
1636         {
1637             if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) headerSz=3;
1638             XMLSTR b2=myMultiByteToWideChar((const char*)(buf+headerSz),l-headerSz);
1639             free(buf); buf=(unsigned char*)b2; headerSz=0;
1640         } else
1641         {
1642             if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
1643             if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
1644         }
1645     }
1646 #else
1647     if (guessUnicodeChars)
1648     {
1649         if (myIsTextUnicode(buf,l))
1650         {
1651             l/=sizeof(wchar_t);
1652             if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
1653             if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
1654             char *b2=myWideCharToMultiByte((const wchar_t*)(buf+headerSz),l-headerSz);
1655             free(buf); buf=(unsigned char*)b2; headerSz=0;
1656         } else
1657         {
1658             if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) headerSz=3;
1659         }
1660     }
1661 #endif
1662
1663     if (!buf) { if (pResults) pResults->error=eXMLErrorCharConversionError; return emptyXMLNode; }
1664     XMLNode x=parseString((XMLSTR)(buf+headerSz),tag,pResults);
1665     free(buf);
1666     return x;
1667 }
1668
1669 static inline void charmemset(XMLSTR dest,XMLCHAR c,int l) { while (l--) *(dest++)=c; }
1670 // private:
1671 // Creates an user friendly XML string from a given element with
1672 // appropriate white space and carriage returns.
1673 //
1674 // This recurses through all subnodes then adds contents of the nodes to the
1675 // string.
1676 int XMLNode::CreateXMLStringR(XMLNodeData *pEntry, XMLSTR lpszMarker, int nFormat)
1677 {
1678     int nResult = 0;
1679     int cb;
1680     int cbElement;
1681     int nChildFormat=-1;
1682     int nElementI=pEntry->nChild+pEntry->nText+pEntry->nClear;
1683     int i,j;
1684
1685     assert(pEntry);
1686
1687 #define LENSTR(lpsz) (lpsz ? _tcslen(lpsz) : 0)
1688
1689     // If the element has no name then assume this is the head node.
1690     cbElement = (int)LENSTR(pEntry->lpszName);
1691
1692     if (cbElement)
1693     {
1694         // "<elementname "
1695         cb = nFormat == -1 ? 0 : nFormat;
1696
1697         if (lpszMarker)
1698         {
1699             if (cb) charmemset(lpszMarker, INDENTCHAR, sizeof(XMLCHAR)*cb);
1700             nResult = cb;
1701             lpszMarker[nResult++]=_T('<');
1702             if (pEntry->isDeclaration) lpszMarker[nResult++]=_T('?');
1703             _tcscpy(&lpszMarker[nResult], pEntry->lpszName);
1704             nResult+=cbElement;
1705             lpszMarker[nResult++]=_T(' ');
1706
1707         } else
1708         {
1709             nResult+=cbElement+2+cb;
1710             if (pEntry->isDeclaration) nResult++;
1711         }
1712
1713         // Enumerate attributes and add them to the string
1714         XMLAttribute *pAttr=pEntry->pAttribute;
1715         for (i=0; i<pEntry->nAttribute; i++)
1716         {
1717             // "Attrib
1718             cb = (int)LENSTR(pAttr->lpszName);
1719             if (cb)
1720             {
1721                 if (lpszMarker) _tcscpy(&lpszMarker[nResult], pAttr->lpszName);
1722                 nResult += cb;
1723                 // "Attrib=Value "
1724                 if (pAttr->lpszValue)
1725                 {
1726                     cb=(int)lengthXMLString(pAttr->lpszValue);
1727                     if (lpszMarker)
1728                     {
1729                         lpszMarker[nResult]=_T('=');
1730                         lpszMarker[nResult+1]=_T('"');
1731                         if (cb) toXMLString(&lpszMarker[nResult+2],pAttr->lpszValue);
1732                         lpszMarker[nResult+cb+2]=_T('"');
1733                     }
1734                     nResult+=cb+3;
1735                 }
1736                 if (lpszMarker) lpszMarker[nResult] = _T(' ');
1737                 nResult++;
1738             }
1739             pAttr++;
1740         }
1741
1742         if (pEntry->isDeclaration)
1743         {
1744             if (lpszMarker)
1745             {
1746                 lpszMarker[nResult-1]=_T('?');
1747                 lpszMarker[nResult]=_T('>');
1748             }
1749             nResult++;
1750             if (nFormat!=-1)
1751             {
1752                 if (lpszMarker) lpszMarker[nResult]=_T('\n');
1753                 nResult++;
1754             }
1755         } else
1756             // If there are child nodes we need to terminate the start tag
1757             if (nElementI)
1758             {
1759                 if (lpszMarker) lpszMarker[nResult-1]=_T('>');
1760                 if (nFormat!=-1)
1761                 {
1762                     if (lpszMarker) lpszMarker[nResult]=_T('\n');
1763                     nResult++;
1764                 }
1765             } else nResult--;
1766     }
1767
1768     // Calculate the child format for when we recurse.  This is used to
1769     // determine the number of spaces used for prefixes.
1770     if (nFormat!=-1)
1771     {
1772         if (cbElement&&(!pEntry->isDeclaration)) nChildFormat=nFormat+1;
1773         else nChildFormat=nFormat;
1774     }
1775
1776     // Enumerate through remaining children
1777     for (i=0; i<nElementI; i++)
1778     {
1779         j=pEntry->pOrder[i];
1780         switch((XMLElementType)(j&3))
1781         {
1782         // Text nodes
1783         case eNodeText:
1784             {
1785                 // "Text"
1786                 XMLCSTR pChild=pEntry->pText[j>>2];
1787                 cb = (int)lengthXMLString(pChild);
1788                 if (cb)
1789                 {
1790                     if (nFormat!=-1)
1791                     {
1792                         if (lpszMarker)
1793                         {
1794                             charmemset(&lpszMarker[nResult],INDENTCHAR,sizeof(XMLCHAR)*(nFormat + 1));
1795                             toXMLString(&lpszMarker[nResult+nFormat+1],pChild);
1796                             lpszMarker[nResult+nFormat+1+cb]=_T('\n');
1797                         }
1798                         nResult+=cb+nFormat+2;
1799                     } else
1800                     {
1801                         if (lpszMarker) toXMLString(&lpszMarker[nResult], pChild);
1802                         nResult += cb;
1803                     }
1804                 }
1805                 break;
1806             }
1807
1808         // Clear type nodes
1809         case eNodeClear:
1810             {
1811                 XMLClear *pChild=pEntry->pClear+(j>>2);
1812                 // "OpenTag"
1813                 cb = (int)LENSTR(pChild->lpszOpenTag);
1814                 if (cb)
1815                 {
1816                     if (nFormat!=-1)
1817                     {
1818                         if (lpszMarker)
1819                         {
1820                             charmemset(&lpszMarker[nResult], INDENTCHAR, sizeof(XMLCHAR)*(nFormat + 1));
1821                             _tcscpy(&lpszMarker[nResult+nFormat+1], pChild->lpszOpenTag);
1822                         }
1823                         nResult+=cb+nFormat+1;
1824                     }
1825                     else
1826                     {
1827                         if (lpszMarker)_tcscpy(&lpszMarker[nResult], pChild->lpszOpenTag);
1828                         nResult += cb;
1829                     }
1830                 }
1831
1832                 // "OpenTag Value"
1833                 cb = (int)LENSTR(pChild->lpszValue);
1834                 if (cb)
1835                 {
1836                     if (lpszMarker) _tcscpy(&lpszMarker[nResult], pChild->lpszValue);
1837                     nResult += cb;
1838                 }
1839
1840                 // "OpenTag Value CloseTag"
1841                 cb = (int)LENSTR(pChild->lpszCloseTag);
1842                 if (cb)
1843                 {
1844                     if (lpszMarker) _tcscpy(&lpszMarker[nResult], pChild->lpszCloseTag);
1845                     nResult += cb;
1846                 }
1847
1848                 if (nFormat!=-1)
1849                 {
1850                     if (lpszMarker) lpszMarker[nResult] = _T('\n');
1851                     nResult++;
1852                 }
1853                 break;
1854             }
1855
1856         // Element nodes
1857         case eNodeChild:
1858             {
1859                 // Recursively add child nodes
1860                 nResult += CreateXMLStringR(pEntry->pChild[j>>2].d, lpszMarker ? lpszMarker + nResult : 0, nChildFormat);
1861                 break;
1862             }
1863         default: break;
1864         }
1865     }
1866
1867     if ((cbElement)&&(!pEntry->isDeclaration))
1868     {
1869         // If we have child entries we need to use long XML notation for
1870         // closing the element - "<elementname>blah blah blah</elementname>"
1871         if (nElementI)
1872         {
1873             // "</elementname>\0"
1874             if (lpszMarker)
1875             {
1876                 if (nFormat != -1)
1877                 {
1878                     if (nFormat)
1879                     {
1880                         charmemset(&lpszMarker[nResult], INDENTCHAR,sizeof(XMLCHAR)*nFormat);
1881                         nResult+=nFormat;
1882                     }
1883                 }
1884
1885                 _tcscpy(&lpszMarker[nResult], _T("</"));
1886                 nResult += 2;
1887                 _tcscpy(&lpszMarker[nResult], pEntry->lpszName);
1888                 nResult += cbElement;
1889
1890                 if (nFormat == -1)
1891                 {
1892                     _tcscpy(&lpszMarker[nResult], _T(">"));
1893                     nResult++;
1894                 } else
1895                 {
1896                     _tcscpy(&lpszMarker[nResult], _T(">\n"));
1897                     nResult+=2;
1898                 }
1899             } else
1900             {
1901                 if (nFormat != -1) nResult+=cbElement+4+nFormat;
1902                 else nResult+=cbElement+3;
1903             }
1904         } else
1905         {
1906             // If there are no children we can use shorthand XML notation -
1907             // "<elementname/>"
1908             // "/>\0"
1909             if (lpszMarker)
1910             {
1911                 if (nFormat == -1)
1912                 {
1913                     _tcscpy(&lpszMarker[nResult], _T("/>"));
1914                     nResult += 2;
1915                 }
1916                 else
1917                 {
1918                     _tcscpy(&lpszMarker[nResult], _T("/>\n"));
1919                     nResult += 3;
1920                 }
1921             }
1922             else
1923             {
1924                 nResult += nFormat == -1 ? 2 : 3;
1925             }
1926         }
1927     }
1928
1929     return nResult;
1930 }
1931
1932 #undef LENSTR
1933
1934 // Create an XML string
1935 // @param       int nFormat             - 0 if no formatting is required
1936 //                                        otherwise nonzero for formatted text
1937 //                                        with carriage returns and indentation.
1938 // @param       int *pnSize             - [out] pointer to the size of the
1939 //                                        returned string not including the
1940 //                                        NULL terminator.
1941 // @return      XMLSTR                  - Allocated XML string, you must free
1942 //                                        this with free().
1943 XMLSTR XMLNode::createXMLString(int nFormat, int *pnSize) const
1944 {
1945     if (!d) { if (pnSize) *pnSize=0; return NULL; }
1946
1947     XMLSTR lpszResult = NULL;
1948     int cbStr;
1949
1950     // Recursively Calculate the size of the XML string
1951     if (!dropWhiteSpace) nFormat=0;
1952     nFormat = nFormat ? 0 : -1;
1953     cbStr = CreateXMLStringR(d, 0, nFormat);
1954     assert(cbStr);
1955     // Alllocate memory for the XML string + the NULL terminator and
1956     // create the recursively XML string.
1957     lpszResult=(XMLSTR)malloc((cbStr+1)*sizeof(XMLCHAR));
1958     CreateXMLStringR(d, lpszResult, nFormat);
1959     if (pnSize) *pnSize = cbStr;
1960     return lpszResult;
1961 }
1962
1963 XMLNode::~XMLNode() { deleteNodeContent(); }
1964
1965 int XMLNode::detachFromParent(XMLNodeData *d)
1966 {
1967     XMLNode *pa=d->pParent->pChild;
1968     int i=0;
1969     while (((void*)(pa[i].d))!=((void*)d)) i++;
1970     d->pParent->nChild--;
1971     if (d->pParent->nChild) memmove(pa+i,pa+i+1,(d->pParent->nChild-i)*sizeof(XMLNode));
1972     else { free(pa); d->pParent->pChild=NULL; }
1973     return removeOrderElement(d->pParent,eNodeChild,i);
1974 }
1975
1976 void XMLNode::deleteNodeContent(char force)
1977 {
1978     if (!d) return;
1979     (d->ref_count) --;
1980     if ((d->ref_count==0)||force)
1981     {
1982         int i;
1983         if (d->pParent) detachFromParent(d);
1984         for(i=0; i<d->nChild; i++) { d->pChild[i].d->pParent=NULL; d->pChild[i].deleteNodeContent(force); }
1985         free(d->pChild);
1986         for(i=0; i<d->nText; i++) free((void*)d->pText[i]);
1987         free(d->pText);
1988         for(i=0; i<d->nClear; i++) free((void*)d->pClear[i].lpszValue);
1989         free(d->pClear);
1990         for(i=0; i<d->nAttribute; i++)
1991         {
1992             free((void*)d->pAttribute[i].lpszName);
1993             if (d->pAttribute[i].lpszValue) free((void*)d->pAttribute[i].lpszValue);
1994         }
1995         free(d->pAttribute);
1996         free(d->pOrder);
1997         free((void*)d->lpszName);
1998         free(d);
1999         d=NULL;
2000     }
2001 }
2002
2003 XMLNode XMLNode::addChild(XMLNode childNode, int pos)
2004 {
2005     XMLNodeData *dc=childNode.d;
2006     if ((!dc)||(!d)) return childNode;
2007     if (dc->pParent) { if ((detachFromParent(dc)<=pos)&&(dc->pParent==d)) pos--; } else dc->ref_count++;
2008     dc->pParent=d;
2009 //     int nc=d->nChild;
2010 //     d->pChild=(XMLNode*)myRealloc(d->pChild,(nc+1),memoryIncrease,sizeof(XMLNode));
2011     d->pChild=(XMLNode*)addToOrder(0,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
2012     d->pChild[pos].d=dc;
2013     d->nChild++;
2014     return childNode;
2015 }
2016
2017 void XMLNode::deleteAttribute(int i)
2018 {
2019     if ((!d)||(i<0)||(i>=d->nAttribute)) return;
2020     d->nAttribute--;
2021     XMLAttribute *p=d->pAttribute+i;
2022     free((void*)p->lpszName);
2023     if (p->lpszValue) free((void*)p->lpszValue);
2024     if (d->nAttribute) memmove(p,p+1,(d->nAttribute-i)*sizeof(XMLAttribute)); else { free(p); d->pAttribute=NULL; }
2025 }
2026
2027 void XMLNode::deleteAttribute(XMLAttribute *a){ if (a) deleteAttribute(a->lpszName); }
2028 void XMLNode::deleteAttribute(XMLCSTR lpszName)
2029 {
2030     int j=0;
2031     getAttribute(lpszName,&j);
2032     if (j) deleteAttribute(j-1);
2033 }
2034
2035 XMLAttribute *XMLNode::updateAttribute_WOSD(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,int i)
2036 {
2037     if (!d) return NULL;
2038     if (i>=d->nAttribute)
2039     {
2040         if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
2041         return NULL;
2042     }
2043     XMLAttribute *p=d->pAttribute+i;
2044     if (p->lpszValue&&p->lpszValue!=lpszNewValue) free((void*)p->lpszValue);
2045     p->lpszValue=lpszNewValue;
2046     if (lpszNewName&&p->lpszName!=lpszNewName) { free((void*)p->lpszName); p->lpszName=lpszNewName; };
2047     return p;
2048 }
2049
2050 XMLAttribute *XMLNode::updateAttribute_WOSD(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
2051 {
2052     if (oldAttribute) return updateAttribute_WOSD(newAttribute->lpszValue,newAttribute->lpszName,oldAttribute->lpszName);
2053     return addAttribute_WOSD(newAttribute->lpszName,newAttribute->lpszValue);
2054 }
2055
2056 XMLAttribute *XMLNode::updateAttribute_WOSD(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,XMLCSTR lpszOldName)
2057 {
2058     int j=0;
2059     getAttribute(lpszOldName,&j);
2060     if (j) return updateAttribute_WOSD(lpszNewValue,lpszNewName,j-1);
2061     else
2062     {
2063         if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
2064         else             return addAttribute_WOSD(stringDup(lpszOldName),lpszNewValue);
2065     }
2066 }
2067
2068 int XMLNode::indexText(XMLCSTR lpszValue) const
2069 {
2070     if (!d) return -1;
2071     int i,l=d->nText;
2072     if (!lpszValue) { if (l) return 0; return -1; }
2073     XMLCSTR *p=d->pText;
2074     for (i=0; i<l; i++) if (lpszValue==p[i]) return i;
2075     return -1;
2076 }
2077
2078 void XMLNode::deleteText(int i)
2079 {
2080     if ((!d)||(i<0)||(i>=d->nText)) return;
2081     d->nText--;
2082     XMLCSTR *p=d->pText+i;
2083     free((void*)*p);
2084     if (d->nText) memmove(p,p+1,(d->nText-i)*sizeof(XMLCSTR)); else { free(p); d->pText=NULL; }
2085     removeOrderElement(d,eNodeText,i);
2086 }
2087
2088 void XMLNode::deleteText(XMLCSTR lpszValue) { deleteText(indexText(lpszValue)); }
2089
2090 XMLCSTR XMLNode::updateText_WOSD(XMLCSTR lpszNewValue, int i)
2091 {
2092     if (!d) return NULL;
2093     if (i>=d->nText) return addText_WOSD(lpszNewValue);
2094     XMLCSTR *p=d->pText+i;
2095     if (*p!=lpszNewValue) { free((void*)*p); *p=lpszNewValue; }
2096     return lpszNewValue;
2097 }
2098
2099 XMLCSTR XMLNode::updateText_WOSD(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
2100 {
2101     if (!d) return NULL;
2102     int i=indexText(lpszOldValue);
2103     if (i>=0) return updateText_WOSD(lpszNewValue,i);
2104     return addText_WOSD(lpszNewValue);
2105 }
2106
2107 void XMLNode::deleteClear(int i)
2108 {
2109     if ((!d)||(i<0)||(i>=d->nClear)) return;
2110     d->nClear--;
2111     XMLClear *p=d->pClear+i;
2112     free((void*)p->lpszValue);
2113     if (d->nClear) memmove(p,p+1,(d->nText-i)*sizeof(XMLClear)); else { free(p); d->pClear=NULL; }
2114     removeOrderElement(d,eNodeClear,i);
2115 }
2116
2117 int XMLNode::indexClear(XMLCSTR lpszValue) const
2118 {
2119     if (!d) return -1;
2120     int i,l=d->nClear;
2121     if (!lpszValue) { if (l) return 0; return -1; }
2122     XMLClear *p=d->pClear;
2123     for (i=0; i<l; i++) if (lpszValue==p[i].lpszValue) return i;
2124     return -1;
2125 }
2126
2127 void XMLNode::deleteClear(XMLCSTR lpszValue) { deleteClear(indexClear(lpszValue)); }
2128 void XMLNode::deleteClear(XMLClear *a) { if (a) deleteClear(a->lpszValue); }
2129
2130 XMLClear *XMLNode::updateClear_WOSD(XMLCSTR lpszNewContent, int i)
2131 {
2132     if (!d) return NULL;
2133     if (i>=d->nClear)
2134     {
2135         return addClear_WOSD(XMLClearTags[0].lpszOpen,lpszNewContent,XMLClearTags[0].lpszClose);
2136     }
2137     XMLClear *p=d->pClear+i;
2138     if (lpszNewContent!=p->lpszValue) { free((void*)p->lpszValue); p->lpszValue=lpszNewContent; }
2139     return p;
2140 }
2141
2142 XMLClear *XMLNode::updateClear_WOSD(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
2143 {
2144     if (!d) return NULL;
2145     int i=indexClear(lpszOldValue);
2146     if (i>=0) return updateClear_WOSD(lpszNewValue,i);
2147     return addClear_WOSD(lpszNewValue,XMLClearTags[0].lpszOpen,XMLClearTags[0].lpszClose);
2148 }
2149
2150 XMLClear *XMLNode::updateClear_WOSD(XMLClear *newP,XMLClear *oldP)
2151 {
2152     if (oldP) return updateClear_WOSD(newP->lpszValue,oldP->lpszValue);
2153     return NULL;
2154 }
2155
2156 XMLNode& XMLNode::operator=( const XMLNode& A )
2157 {
2158     // shallow copy
2159     if (this != &A)
2160     {
2161         deleteNodeContent();
2162         d=A.d;
2163         if (d) (d->ref_count) ++ ;
2164     }
2165     return *this;
2166 }
2167
2168 XMLNode::XMLNode(const XMLNode &A)
2169 {
2170     // shallow copy
2171     d=A.d;
2172     if (d) (d->ref_count)++ ;
2173 }
2174
2175 int XMLNode::nChildNode(XMLCSTR name) const
2176 {
2177     if (!d) return 0;
2178     int i,j=0,n=d->nChild;
2179     XMLNode *pc=d->pChild;
2180     for (i=0; i<n; i++)
2181     {
2182         if (_tcsicmp(pc->d->lpszName, name)==0) j++;
2183         pc++;
2184     }
2185     return j;
2186 }
2187
2188 XMLNode XMLNode::getChildNode(XMLCSTR name, int *j) const
2189 {
2190     if (!d) return emptyXMLNode;
2191     int i=0,n=d->nChild;
2192     if (j) i=*j;
2193     XMLNode *pc=d->pChild+i;
2194     for (; i<n; i++)
2195     {
2196         if (_tcsicmp(pc->d->lpszName, name)==0)
2197         {
2198             if (j) *j=i+1;
2199             return *pc;
2200         }
2201         pc++;
2202     }
2203     return emptyXMLNode;
2204 }
2205
2206 XMLNode XMLNode::getChildNode(XMLCSTR name, int j) const
2207 {
2208     if (!d) return emptyXMLNode;
2209     int i=0;
2210     while (j-->0) getChildNode(name,&i);
2211     return getChildNode(name,&i);
2212 }
2213
2214 int XMLNode::positionOfText     (int i) const { if (i>=d->nText ) i=d->nText-1;  return findPosition(d,i,eNodeText ); }
2215 int XMLNode::positionOfClear    (int i) const { if (i>=d->nClear) i=d->nClear-1; return findPosition(d,i,eNodeClear); }
2216 int XMLNode::positionOfChildNode(int i) const { if (i>=d->nChild) i=d->nChild-1; return findPosition(d,i,eNodeChild); }
2217 int XMLNode::positionOfText (XMLCSTR lpszValue) const { return positionOfText (indexText (lpszValue)); }
2218 int XMLNode::positionOfClear(XMLCSTR lpszValue) const { return positionOfClear(indexClear(lpszValue)); }
2219 int XMLNode::positionOfClear(XMLClear *a) const { if (a) return positionOfClear(a->lpszValue); return positionOfClear(); }
2220 int XMLNode::positionOfChildNode(XMLNode x)  const
2221 {
2222     if ((!d)||(!x.d)) return -1;
2223     XMLNodeData *dd=x.d;
2224     XMLNode *pc=d->pChild;
2225     int i=d->nChild;
2226     while (i--) if (pc[i].d==dd) return findPosition(d,i,eNodeChild);
2227     return -1;
2228 }
2229 int XMLNode::positionOfChildNode(XMLCSTR name, int count) const
2230 {
2231     if (!name) return positionOfChildNode(count);
2232     int j=0;
2233     do { getChildNode(name,&j); if (j<0) return -1; } while (count--);
2234     return findPosition(d,j-1,eNodeChild);
2235 }
2236
2237 XMLNode XMLNode::getChildNodeWithAttribute(XMLCSTR name,XMLCSTR attributeName,XMLCSTR attributeValue, int *k) const
2238 {
2239      int i=0,j;
2240      if (k) i=*k;
2241      XMLNode x;
2242      XMLCSTR t;
2243      do
2244      {
2245          x=getChildNode(name,&i);
2246          if (!x.isEmpty())
2247          {
2248              if (attributeValue)
2249              {
2250                  j=0;
2251                  do
2252                  {
2253                      t=x.getAttribute(attributeName,&j);
2254                      if (t&&(_tcsicmp(attributeValue,t)==0)) { if (k) *k=i+1; return x; }
2255                  } while (t);
2256              } else
2257              {
2258                  if (x.isAttributeSet(attributeName)) { if (k) *k=i+1; return x; }
2259              }
2260          }
2261      } while (!x.isEmpty());
2262      return emptyXMLNode;
2263 }
2264
2265 // Find an attribute on an node.
2266 XMLCSTR XMLNode::getAttribute(XMLCSTR lpszAttrib, int *j) const
2267 {
2268     if (!d) return NULL;
2269     int i=0,n=d->nAttribute;
2270     if (j) i=*j;
2271     XMLAttribute *pAttr=d->pAttribute+i;
2272     for (; i<n; i++)
2273     {
2274         if (_tcsicmp(pAttr->lpszName, lpszAttrib)==0)
2275         {
2276             if (j) *j=i+1;
2277             return pAttr->lpszValue;
2278         }
2279         pAttr++;
2280     }
2281     return NULL;
2282 }
2283
2284 char XMLNode::isAttributeSet(XMLCSTR lpszAttrib) const
2285 {
2286     if (!d) return FALSE;
2287     int i,n=d->nAttribute;
2288     XMLAttribute *pAttr=d->pAttribute;
2289     for (i=0; i<n; i++)
2290     {
2291         if (_tcsicmp(pAttr->lpszName, lpszAttrib)==0)
2292         {
2293             return TRUE;
2294         }
2295         pAttr++;
2296     }
2297     return FALSE;
2298 }
2299
2300 XMLCSTR XMLNode::getAttribute(XMLCSTR name, int j) const
2301 {
2302     if (!d) return NULL;
2303     int i=0;
2304     while (j-->0) getAttribute(name,&i);
2305     return getAttribute(name,&i);
2306 }
2307
2308 XMLNodeContents XMLNode::enumContents(int i) const
2309 {
2310     XMLNodeContents c;
2311     if (!d) { c.type=eNodeNULL; return c; }
2312     if (i<d->nAttribute)
2313     {
2314         c.type=eNodeAttribute;
2315         c.attrib=d->pAttribute[i];
2316         return c;
2317     }
2318     i-=d->nAttribute;
2319     c.type=(XMLElementType)(d->pOrder[i]&3);
2320     i=(d->pOrder[i])>>2;
2321     switch (c.type)
2322     {
2323     case eNodeChild:     c.child = d->pChild[i];      break;
2324     case eNodeText:      c.text  = d->pText[i];       break;
2325     case eNodeClear:     c.clear = d->pClear[i];      break;
2326     default: break;
2327     }
2328     return c;
2329 }
2330
2331 XMLCSTR XMLNode::getName() const { if (!d) return NULL; return d->lpszName;   }
2332 int XMLNode::nText()       const { if (!d) return 0;    return d->nText;      }
2333 int XMLNode::nChildNode()  const { if (!d) return 0;    return d->nChild;     }
2334 int XMLNode::nAttribute()  const { if (!d) return 0;    return d->nAttribute; }
2335 int XMLNode::nClear()      const { if (!d) return 0;    return d->nClear;     }
2336 int XMLNode::nElement()    const { if (!d) return 0;    return d->nAttribute+d->nChild+d->nText+d->nClear; }
2337 XMLClear     XMLNode::getClear         (int i) const { if ((!d)||(i>=d->nClear    )) return emptyXMLClear;     return d->pClear[i];     }
2338 XMLAttribute XMLNode::getAttribute     (int i) const { if ((!d)||(i>=d->nAttribute)) return emptyXMLAttribute; return d->pAttribute[i]; }
2339 XMLCSTR      XMLNode::getAttributeName (int i) const { if ((!d)||(i>=d->nAttribute)) return NULL;              return d->pAttribute[i].lpszName;  }
2340 XMLCSTR      XMLNode::getAttributeValue(int i) const { if ((!d)||(i>=d->nAttribute)) return NULL;              return d->pAttribute[i].lpszValue; }
2341 XMLCSTR      XMLNode::getText          (int i) const { if ((!d)||(i>=d->nText     )) return NULL;              return d->pText[i];      }
2342 XMLNode      XMLNode::getChildNode     (int i) const { if ((!d)||(i>=d->nChild    )) return emptyXMLNode;      return d->pChild[i];     }
2343 XMLNode      XMLNode::getParentNode    (     ) const { if ((!d)||(!d->pParent     )) return emptyXMLNode;      return XMLNode(d->pParent); }
2344 char         XMLNode::isDeclaration    (     ) const { if (!d) return 0;             return d->isDeclaration; }
2345 char         XMLNode::isEmpty          (     ) const { return (d==NULL); }
2346
2347 XMLNode       XMLNode::addChild(XMLCSTR lpszName, char isDeclaration, int pos)
2348               { return addChild_priv(0,stringDup(lpszName),isDeclaration,pos); }
2349 XMLNode       XMLNode::addChild_WOSD(XMLCSTR lpszName, char isDeclaration, int pos)
2350               { return addChild_priv(0,lpszName,isDeclaration,pos); }
2351 XMLAttribute *XMLNode::addAttribute(XMLCSTR lpszName, XMLCSTR lpszValue)
2352               { return addAttribute_priv(0,stringDup(lpszName),stringDup(lpszValue)); }
2353 XMLAttribute *XMLNode::addAttribute_WOSD(XMLCSTR lpszName, XMLCSTR lpszValuev)
2354               { return addAttribute_priv(0,lpszName,lpszValuev); }
2355 XMLCSTR       XMLNode::addText(XMLCSTR lpszValue, int pos)
2356               { return addText_priv(0,stringDup(lpszValue),pos); }
2357 XMLCSTR       XMLNode::addText_WOSD(XMLCSTR lpszValue, int pos)
2358               { return addText_priv(0,lpszValue,pos); }
2359 XMLClear     *XMLNode::addClear(XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
2360               { return addClear_priv(0,stringDup(lpszValue),lpszOpen,lpszClose,pos); }
2361 XMLClear     *XMLNode::addClear_WOSD(XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
2362               { return addClear_priv(0,lpszValue,lpszOpen,lpszClose,pos); }
2363 XMLCSTR       XMLNode::updateName(XMLCSTR lpszName)
2364               { return updateName_WOSD(stringDup(lpszName)); }
2365 XMLAttribute *XMLNode::updateAttribute(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
2366               { return updateAttribute_WOSD(stringDup(newAttribute->lpszValue),stringDup(newAttribute->lpszName),oldAttribute->lpszName); }
2367 XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,int i)
2368               { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),i); }
2369 XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,XMLCSTR lpszOldName)
2370               { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),lpszOldName); }
2371 XMLCSTR       XMLNode::updateText(XMLCSTR lpszNewValue, int i)
2372               { return updateText_WOSD(stringDup(lpszNewValue),i); }
2373 XMLCSTR       XMLNode::updateText(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
2374               { return updateText_WOSD(stringDup(lpszNewValue),lpszOldValue); }
2375 XMLClear     *XMLNode::updateClear(XMLCSTR lpszNewContent, int i)
2376               { return updateClear_WOSD(stringDup(lpszNewContent),i); }
2377 XMLClear     *XMLNode::updateClear(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
2378               { return updateClear_WOSD(stringDup(lpszNewValue),lpszOldValue); }
2379 XMLClear     *XMLNode::updateClear(XMLClear *newP,XMLClear *oldP)
2380               { return updateClear_WOSD(stringDup(newP->lpszValue),oldP->lpszValue); }
2381
2382 void XMLNode::setGlobalOptions(char _guessUnicodeChars, char _strictUTF8Parsing, char _dropWhiteSpace)
2383 {
2384     guessUnicodeChars=_guessUnicodeChars; dropWhiteSpace=_dropWhiteSpace; strictUTF8Parsing=_strictUTF8Parsing;
2385 #ifndef _XMLUNICODE
2386     if (_strictUTF8Parsing) XML_ByteTable=XML_utf8ByteTable; else XML_ByteTable=XML_asciiByteTable;
2387 #endif
2388 }
2389
2390 char XMLNode::guessUTF8ParsingParameterValue(void *buf,int l, char useXMLEncodingAttribute)
2391 {
2392 #ifdef _XMLUNICODE
2393     return 0;
2394 #else
2395     if (l<25) return 0;
2396     if (myIsTextUnicode(buf,l)) return 0;
2397     unsigned char *b=(unsigned char*)buf;
2398     if ((b[0]==0xef)&&(b[1]==0xbb)&&(b[2]==0xbf)) return 1;
2399
2400     // Match utf-8 model ?
2401     int i=0;
2402     while (i<l)
2403         switch (XML_utf8ByteTable[b[i]])
2404         {
2405         case 4: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) return 0; // 10bbbbbb ?
2406         case 3: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) return 0; // 10bbbbbb ?
2407         case 2: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) return 0; // 10bbbbbb ?
2408         case 1: i++; break;
2409         case 0: i=l;
2410         }
2411     if (!useXMLEncodingAttribute) return 1;
2412     // if encoding is specified and different from utf-8 than it's non-utf8
2413     // otherwise it's utf-8
2414     char bb[201];
2415     l=mmin(l,200);
2416     memcpy(bb,buf,l); // copy buf into bb to be able to do "bb[l]=0"
2417     bb[l]=0;
2418     b=(unsigned char*)strstr(bb,"encoding");
2419     if (!b) return 1;
2420     b+=8; while XML_isSPACECHAR(*b) b++; if (*b!='=') return 1;
2421     b++;  while XML_isSPACECHAR(*b) b++; if ((*b!='\'')&&(*b!='"')) return 1;
2422     b++;  while XML_isSPACECHAR(*b) b++; if ((_strnicmp((char*)b,"utf-8",5)==0)||
2423                                              (_strnicmp((char*)b,"utf8",4)==0)) return 1;
2424     return 0;
2425 #endif
2426 }
2427 #undef XML_isSPACECHAR
2428
2429 //////////////////////////////////////////////////////////
2430 //      Here starts the base64 conversion functions.    //
2431 //////////////////////////////////////////////////////////
2432
2433 static const char base64Fillchar = _T('='); // used to mark partial words at the end
2434
2435 // this lookup table defines the base64 encoding
2436 XMLCSTR base64EncodeTable=_T("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
2437
2438 // Decode Table gives the index of any valid base64 character in the Base64 table]
2439 // 96: '='  -   97: space char   -   98: illegal char   -   99: end of string
2440 const unsigned char base64DecodeTable[] = {
2441     99,98,98,98,98,98,98,98,98,97,  97,98,98,97,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //00 -29
2442     98,98,97,98,98,98,98,98,98,98,  98,98,98,62,98,98,98,63,52,53,  54,55,56,57,58,59,60,61,98,98,  //30 -59
2443     98,96,98,98,98, 0, 1, 2, 3, 4,   5, 6, 7, 8, 9,10,11,12,13,14,  15,16,17,18,19,20,21,22,23,24,  //60 -89
2444     25,98,98,98,98,98,98,26,27,28,  29,30,31,32,33,34,35,36,37,38,  39,40,41,42,43,44,45,46,47,48,  //90 -119
2445     49,50,51,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //120 -149
2446     98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //150 -179
2447     98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //180 -209
2448     98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //210 -239
2449     98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98                                               //240 -255
2450 };
2451
2452 XMLParserBase64Tool::~XMLParserBase64Tool(){ freeBuffer(); }
2453
2454 void XMLParserBase64Tool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; }
2455
2456 int XMLParserBase64Tool::encodeLength(int inlen, char formatted)
2457 {
2458     unsigned int i=((inlen-1)/3*4+4+1);
2459     if (formatted) i+=inlen/54;
2460     return i;
2461 }
2462
2463 XMLSTR XMLParserBase64Tool::encode(unsigned char *inbuf, unsigned int inlen, char formatted)
2464 {
2465     int i=encodeLength(inlen,formatted),k=17,eLen=inlen/3,j;
2466     alloc(i*sizeof(XMLCHAR));
2467     XMLSTR curr=(XMLSTR)buf;
2468     for(i=0;i<eLen;i++)
2469     {
2470         // Copy next three bytes into lower 24 bits of int, paying attention to sign.
2471         j=(inbuf[0]<<16)|(inbuf[1]<<8)|inbuf[2]; inbuf+=3;
2472         // Encode the int into four chars
2473         *(curr++)=base64EncodeTable[ j>>18      ];
2474         *(curr++)=base64EncodeTable[(j>>12)&0x3f];
2475         *(curr++)=base64EncodeTable[(j>> 6)&0x3f];
2476         *(curr++)=base64EncodeTable[(j    )&0x3f];
2477         if (formatted) { if (!k) { *(curr++)=_T('\n'); k=18; } k--; }
2478     }
2479     eLen=inlen-eLen*3; // 0 - 2.
2480     if (eLen==1)
2481     {
2482         *(curr++)=base64EncodeTable[ inbuf[0]>>2      ];
2483         *(curr++)=base64EncodeTable[(inbuf[0]<<4)&0x3F];
2484         *(curr++)=base64Fillchar;
2485         *(curr++)=base64Fillchar;
2486     } else if (eLen==2)
2487     {
2488         j=(inbuf[0]<<8)|inbuf[1];
2489         *(curr++)=base64EncodeTable[ j>>10      ];
2490         *(curr++)=base64EncodeTable[(j>> 4)&0x3f];
2491         *(curr++)=base64EncodeTable[(j<< 2)&0x3f];
2492         *(curr++)=base64Fillchar;
2493     }
2494     *(curr++)=0;
2495     return (XMLSTR)buf;
2496 }
2497
2498 unsigned int XMLParserBase64Tool::decodeSize(XMLCSTR data,XMLError *xe)
2499 {
2500      if (xe) *xe=eXMLErrorNone;
2501     int size=0;
2502     unsigned char c;
2503     //skip any extra characters (e.g. newlines or spaces)
2504     while (*data)
2505     {
2506 #ifdef _XMLUNICODE
2507         if (*data>255) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
2508 #endif
2509         c=base64DecodeTable[(unsigned char)(*data)];
2510         if (c<97) size++;
2511         else if (c==98) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
2512         data++;
2513     }
2514     if (xe&&(size%4!=0)) *xe=eXMLErrorBase64DataSizeIsNotMultipleOf4;
2515     if (size==0) return 0;
2516     do { data--; size--; } while(*data==base64Fillchar); size++;
2517     return (unsigned int)((size*3)/4);
2518 }
2519
2520 unsigned char XMLParserBase64Tool::decode(XMLCSTR data, unsigned char *buf, int len, XMLError *xe)
2521 {
2522     if (xe) *xe=eXMLErrorNone;
2523     int i=0,p=0;
2524     unsigned char d,c;
2525     for(;;)
2526     {
2527
2528 #ifdef _XMLUNICODE
2529 #define BASE64DECODE_READ_NEXT_CHAR(c)                                              \
2530         do {                                                                        \
2531             if (data[i]>255){ c=98; break; }                                        \
2532             c=base64DecodeTable[(unsigned char)data[i++]];                       \
2533         }while (c==97);                                                             \
2534         if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
2535 #else
2536 #define BASE64DECODE_READ_NEXT_CHAR(c)                                           \
2537         do { c=base64DecodeTable[(unsigned char)data[i++]]; }while (c==97);   \
2538         if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
2539 #endif
2540
2541         BASE64DECODE_READ_NEXT_CHAR(c)
2542         if (c==99) { return 2; }
2543         if (c==96)
2544         {
2545             if (p==(int)len) return 2;
2546             if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;
2547             return 1;
2548         }
2549
2550         BASE64DECODE_READ_NEXT_CHAR(d)
2551         if ((d==99)||(d==96)) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
2552         if (p==(int)len) {      if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall; return 0; }
2553         buf[p++]=(c<<2)|((d>>4)&0x3);
2554
2555         BASE64DECODE_READ_NEXT_CHAR(c)
2556         if (c==99) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
2557         if (p==(int)len)
2558         {
2559             if (c==96) return 2;
2560             if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
2561             return 0;
2562         }
2563         if (c==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
2564         buf[p++]=((d<<4)&0xf0)|((c>>2)&0xf);
2565
2566         BASE64DECODE_READ_NEXT_CHAR(d)
2567         if (d==99 ) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
2568         if (p==(int)len)
2569         {
2570             if (d==96) return 2;
2571             if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
2572             return 0;
2573         }
2574         if (d==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
2575         buf[p++]=((c<<6)&0xc0)|d;
2576     }
2577 }
2578 #undef BASE64DECODE_READ_NEXT_CHAR
2579
2580 void XMLParserBase64Tool::alloc(int newsize)
2581 {
2582     if ((!buf)&&(newsize)) { buf=malloc(newsize); buflen=newsize; return; }
2583     if (newsize>buflen) { buf=realloc(buf,newsize); buflen=newsize; }
2584 }
2585
2586 unsigned char *XMLParserBase64Tool::decode(XMLCSTR data, int *outlen, XMLError *xe)
2587 {
2588     if (xe) *xe=eXMLErrorNone;
2589     unsigned int len=decodeSize(data,xe);
2590     if (outlen) *outlen=len;
2591     if (!len) return NULL;
2592     alloc(len+1);
2593     if(!decode(data,(unsigned char*)buf,len,xe)){ return NULL; }
2594     return (unsigned char*)buf;
2595 }
2596