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