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