PageRenderTime 63ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/dep/ssl-vision/src/shared/vartypes/xml/xmlParser.cpp

https://bitbucket.org/jlisee/iccomp2010
C++ | 2608 lines | 2019 code | 223 blank | 366 comment | 405 complexity | 85c8ee5b32b95ac6b5a366627e648966 MD5 | raw file
Possible License(s): GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. /**
  2. ****************************************************************************
  3. * <P> XML.c - implementation file for basic XML parser written in ANSI C++
  4. * for portability. It works by using recursion and a node tree for breaking
  5. * down the elements of an XML document. </P>
  6. *
  7. * @version V2.23
  8. * @author Frank Vanden Berghen
  9. *
  10. * NOTE:
  11. *
  12. * If you add "#define STRICT_PARSING", on the first line of this file
  13. * the parser will see the following XML-stream:
  14. * <a><b>some text</b><b>other text </a>
  15. * as an error. Otherwise, this tring will be equivalent to:
  16. * <a><b>some text</b><b>other text</b></a>
  17. *
  18. * NOTE:
  19. *
  20. * If you add "#define APPROXIMATE_PARSING" on the first line of this file
  21. * the parser will see the following XML-stream:
  22. * <data name="n1">
  23. * <data name="n2">
  24. * <data name="n3" />
  25. * as equivalent to the following XML-stream:
  26. * <data name="n1" />
  27. * <data name="n2" />
  28. * <data name="n3" />
  29. * This can be useful for badly-formed XML-streams but prevent the use
  30. * of the following XML-stream (problem is: tags at contiguous levels
  31. * have the same names):
  32. * <data name="n1">
  33. * <data name="n2">
  34. * <data name="n3" />
  35. * </data>
  36. * </data>
  37. *
  38. * NOTE:
  39. *
  40. * If you add "#define _XMLPARSER_NO_MESSAGEBOX_" on the first line of this file
  41. * the "openFileHelper" function will always display error messages inside the
  42. * console instead of inside a message-box-window. Message-box-windows are
  43. * available on windows 9x/NT/2000/XP/Vista only.
  44. *
  45. * BSD license:
  46. * Copyright (c) 2002, Frank Vanden Berghen
  47. * All rights reserved.
  48. * Redistribution and use in source and binary forms, with or without
  49. * modification, are permitted provided that the following conditions are met:
  50. *
  51. * * Redistributions of source code must retain the above copyright
  52. * notice, this list of conditions and the following disclaimer.
  53. * * Redistributions in binary form must reproduce the above copyright
  54. * notice, this list of conditions and the following disclaimer in the
  55. * documentation and/or other materials provided with the distribution.
  56. * * Neither the name of the Frank Vanden Berghen nor the
  57. * names of its contributors may be used to endorse or promote products
  58. * derived from this software without specific prior written permission.
  59. *
  60. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
  61. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  62. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  63. * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
  64. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  65. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  66. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  67. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  68. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  69. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  70. *
  71. ****************************************************************************
  72. */
  73. #ifndef _CRT_SECURE_NO_DEPRECATE
  74. #define _CRT_SECURE_NO_DEPRECATE
  75. #endif
  76. #include "xmlParser.h"
  77. #include <cstdio>
  78. namespace VarTypes {
  79. #ifdef _XMLWINDOWS
  80. //#ifdef _DEBUG
  81. //#define _CRTDBG_MAP_ALLOC
  82. //#include <crtdbg.h>
  83. //#endif
  84. #define WIN32_LEAN_AND_MEAN
  85. #include <Windows.h> // to have IsTextUnicode, MultiByteToWideChar, WideCharToMultiByte to handle unicode files
  86. // to have "MessageBoxA" to display error messages for openFilHelper
  87. #endif
  88. #include <memory.h>
  89. #include <assert.h>
  90. #include <stdio.h>
  91. #include <string.h>
  92. #include <stdlib.h>
  93. XMLCSTR XMLNode::getVersion() { return _T("v2.23"); }
  94. void free_XMLDLL(void *t){free(t);}
  95. static char strictUTF8Parsing=1, guessUnicodeChars=1, dropWhiteSpace=1;
  96. inline int mmin( const int t1, const int t2 ) { return t1 < t2 ? t1 : t2; }
  97. // You can modify the initialization of the variable "XMLClearTags" below
  98. // to change the clearTags that are currently recognized by the library.
  99. // The number on the second columns is the length of the string inside the
  100. // first column. The "<!DOCTYPE" declaration must be the second in the list.
  101. static ALLXMLClearTag XMLClearTags[] =
  102. {
  103. { _T("<![CDATA["),9, _T("]]>") },
  104. { _T("<!DOCTYPE"),9, _T(">") },
  105. { _T("<PRE>") ,5, _T("</PRE>") },
  106. { _T("<Script>") ,8, _T("</Script>")},
  107. { _T("<!--") ,4, _T("-->") },
  108. { NULL ,0, NULL }
  109. };
  110. ALLXMLClearTag* XMLNode::getClearTagTable() { return XMLClearTags; }
  111. // You can modify the initialization of the variable "XMLEntities" below
  112. // to change the character entities that are currently recognized by the library.
  113. // The number on the second columns is the length of the string inside the
  114. // first column. Additionally, the syntaxes "&#xA0;" and "&#160;" are recognized.
  115. typedef struct { XMLCSTR s; int l; XMLCHAR c;} XMLCharacterEntity;
  116. static XMLCharacterEntity XMLEntities[] =
  117. {
  118. { _T("&amp;" ), 5, _T('&' )},
  119. { _T("&lt;" ), 4, _T('<' )},
  120. { _T("&gt;" ), 4, _T('>' )},
  121. { _T("&quot;"), 6, _T('\"')},
  122. { _T("&apos;"), 6, _T('\'')},
  123. { NULL , 0, '\0' }
  124. };
  125. // When rendering the XMLNode to a string (using the "createXMLString" function),
  126. // you can ask for a beautiful formatting. This formatting is using the
  127. // following indentation character:
  128. #define INDENTCHAR _T('\t')
  129. // The following function parses the XML errors into a user friendly string.
  130. // You can edit this to change the output language of the library to something else.
  131. XMLCSTR XMLNode::getError(XMLError xerror)
  132. {
  133. switch (xerror)
  134. {
  135. case eXMLErrorNone: return _T("No error");
  136. case eXMLErrorMissingEndTag: return _T("Warning: Unmatched end tag");
  137. case eXMLErrorEmpty: return _T("Error: No XML data");
  138. case eXMLErrorFirstNotStartTag: return _T("Error: First token not start tag");
  139. case eXMLErrorMissingTagName: return _T("Error: Missing start tag name");
  140. case eXMLErrorMissingEndTagName: return _T("Error: Missing end tag name");
  141. case eXMLErrorNoMatchingQuote: return _T("Error: Unmatched quote");
  142. case eXMLErrorUnmatchedEndTag: return _T("Error: Unmatched end tag");
  143. case eXMLErrorUnmatchedEndClearTag: return _T("Error: Unmatched clear tag end");
  144. case eXMLErrorUnexpectedToken: return _T("Error: Unexpected token found");
  145. case eXMLErrorInvalidTag: return _T("Error: Invalid tag found");
  146. case eXMLErrorNoElements: return _T("Error: No elements found");
  147. case eXMLErrorFileNotFound: return _T("Error: File not found");
  148. case eXMLErrorFirstTagNotFound: return _T("Error: First Tag not found");
  149. case eXMLErrorUnknownCharacterEntity:return _T("Error: Unknown character entity");
  150. case eXMLErrorCharConversionError: return _T("Error: unable to convert between UNICODE and MultiByte chars");
  151. case eXMLErrorCannotOpenWriteFile: return _T("Error: unable to open file for writing");
  152. case eXMLErrorCannotWriteFile: return _T("Error: cannot write into file");
  153. case eXMLErrorBase64DataSizeIsNotMultipleOf4: return _T("Warning: Base64-string length is not a multiple of 4");
  154. case eXMLErrorBase64DecodeTruncatedData: return _T("Warning: Base64-string is truncated");
  155. case eXMLErrorBase64DecodeIllegalCharacter: return _T("Error: Base64-string contains an illegal character");
  156. case eXMLErrorBase64DecodeBufferTooSmall: return _T("Error: Base64 decode output buffer is too small");
  157. };
  158. return _T("Unknown");
  159. }
  160. // Here is an abstraction layer to access some common string manipulation functions.
  161. // The abstraction layer is currently working for gcc, Microsoft Visual Studio 6.0,
  162. // Microsoft Visual Studio .NET, CC (sun compiler) and Borland C++.
  163. // If you plan to "port" the library to a new system/compiler, all you have to do is
  164. // to edit the following lines.
  165. #ifdef XML_NO_WIDE_CHAR
  166. char myIsTextUnicode(const void *b, int len) { (void)b; (void)len; return FALSE; }
  167. #else
  168. #if defined (UNDER_CE) || !defined(WIN32)
  169. char myIsTextUnicode(const void *b, int len) // inspired by the Wine API: RtlIsTextUnicode
  170. {
  171. #ifdef sun
  172. // for SPARC processors: wchar_t* buffers must always be alligned, otherwise it's a char* buffer.
  173. if ((((unsigned long)b)%sizeof(wchar_t))!=0) return FALSE;
  174. #endif
  175. const wchar_t *s=(const wchar_t*)b;
  176. // buffer too small:
  177. if (len<(int)sizeof(wchar_t)) return FALSE;
  178. // odd length test
  179. if (len&1) return FALSE;
  180. /* only checks the first 256 characters */
  181. len=mmin(256,len/sizeof(wchar_t));
  182. // Check for the special byte order:
  183. if (*s == 0xFFFE) return FALSE; // IS_TEXT_UNICODE_REVERSE_SIGNATURE;
  184. if (*s == 0xFEFF) return TRUE; // IS_TEXT_UNICODE_SIGNATURE
  185. // checks for ASCII characters in the UNICODE stream
  186. int i,stats=0;
  187. for (i=0; i<len; i++) if (s[i]<=(unsigned short)255) stats++;
  188. if (stats>len/2) return TRUE;
  189. // Check for UNICODE NULL chars
  190. for (i=0; i<len; i++) if (!s[i]) return TRUE;
  191. return FALSE;
  192. }
  193. #else
  194. char myIsTextUnicode(const void *b,int l) { return (char)IsTextUnicode((CONST LPVOID)b,l,NULL); };
  195. #endif
  196. #endif
  197. #ifdef _XMLWINDOWS
  198. // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET,
  199. #ifdef _XMLUNICODE
  200. wchar_t *myMultiByteToWideChar(const char *s,int l)
  201. {
  202. int i;
  203. if (strictUTF8Parsing) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,l,NULL,0);
  204. else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,l,NULL,0);
  205. if (i<0) return NULL;
  206. wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(XMLCHAR));
  207. if (strictUTF8Parsing) i=(int)MultiByteToWideChar(CP_UTF8,0 ,s,l,d,i);
  208. else i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,l,d,i);
  209. d[i]=0;
  210. return d;
  211. }
  212. #else
  213. char *myWideCharToMultiByte(const wchar_t *s,int l)
  214. {
  215. UINT codePage=CP_ACP; if (strictUTF8Parsing) codePage=CP_UTF8;
  216. int i=(int)WideCharToMultiByte(codePage, // code page
  217. 0, // performance and mapping flags
  218. s, // wide-character string
  219. l, // number of chars in string
  220. NULL, // buffer for new string
  221. 0, // size of buffer
  222. NULL, // default for unmappable chars
  223. NULL // set when default char used
  224. );
  225. if (i<0) return NULL;
  226. char *d=(char*)malloc(i+1);
  227. WideCharToMultiByte(codePage, // code page
  228. 0, // performance and mapping flags
  229. s, // wide-character string
  230. l, // number of chars in string
  231. d, // buffer for new string
  232. i, // size of buffer
  233. NULL, // default for unmappable chars
  234. NULL // set when default char used
  235. );
  236. d[i]=0;
  237. return d;
  238. }
  239. #endif
  240. #ifdef __BORLANDC__
  241. int _strnicmp(char *c1, char *c2, int l){ return strnicmp(c1,c2,l);}
  242. #endif
  243. #else
  244. // for gcc and CC
  245. #ifdef XML_NO_WIDE_CHAR
  246. char *myWideCharToMultiByte(const wchar_t *s, int l) { (void)s; (void)l; return NULL; }
  247. #else
  248. char *myWideCharToMultiByte(const wchar_t *s, int l)
  249. {
  250. const wchar_t *ss=s;
  251. int i=(int)wcsrtombs(NULL,&ss,0,NULL);
  252. if (i<0) return NULL;
  253. char *d=(char *)malloc(i+1);
  254. wcsrtombs(d,&s,i,NULL);
  255. d[i]=0;
  256. return d;
  257. }
  258. #endif
  259. #ifdef _XMLUNICODE
  260. wchar_t *myMultiByteToWideChar(const char *s, int l)
  261. {
  262. const char *ss=s;
  263. int i=(int)mbsrtowcs(NULL,&ss,0,NULL);
  264. if (i<0) return NULL;
  265. wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(wchar_t));
  266. mbsrtowcs(d,&s,l,NULL);
  267. d[i]=0;
  268. return d;
  269. }
  270. int _tcslen(XMLCSTR c) { return wcslen(c); }
  271. #ifdef sun
  272. // for CC
  273. #include <widec.h>
  274. int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncasecmp(c1,c2,l);}
  275. int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return wscasecmp(c1,c2); }
  276. #else
  277. // for gcc
  278. int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncasecmp(c1,c2,l);}
  279. int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return wcscasecmp(c1,c2); }
  280. #endif
  281. XMLSTR _tcsstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
  282. XMLSTR _tcscpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
  283. FILE *_tfopen(XMLCSTR filename,XMLCSTR mode)
  284. {
  285. char *filenameAscii=myWideCharToMultiByte(filename,0);
  286. FILE *f;
  287. if (mode[0]==_T('r')) f=fopen(filenameAscii,"rb");
  288. else f=fopen(filenameAscii,"wb");
  289. free(filenameAscii);
  290. return f;
  291. }
  292. #else
  293. #if defined(WIN32)
  294. FILE *_tfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
  295. int _tcslen(XMLCSTR c) { return strlen(c); }
  296. int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _strnicmp(c1,c2,l);}
  297. int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return _strnicmp(c1,c2,strlen(c1)>strlen(c2)?strlen(c1):strlen(c2)); }
  298. XMLSTR _tcsstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
  299. XMLSTR _tcscpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
  300. #else
  301. FILE *_tfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
  302. int _tcslen(XMLCSTR c) { return strlen(c); }
  303. int _tcsnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncasecmp(c1,c2,l);}
  304. int _tcsicmp(XMLCSTR c1, XMLCSTR c2) { return strcasecmp(c1,c2); }
  305. XMLSTR _tcsstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
  306. XMLSTR _tcscpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
  307. #endif
  308. #endif
  309. #if defined(WIN32)
  310. #else
  311. int _strnicmp(const char *c1,const char *c2, int l) { return strncasecmp(c1,c2,l);}
  312. #endif
  313. #endif
  314. /////////////////////////////////////////////////////////////////////////
  315. // Here start the core implementation of the XMLParser library //
  316. /////////////////////////////////////////////////////////////////////////
  317. // You should normally not change anything below this point.
  318. // For your own information, I suggest that you read the openFileHelper below:
  319. XMLNode XMLNode::openFileHelper(XMLCSTR filename, XMLCSTR tag)
  320. {
  321. // guess the value of the global parameter "strictUTF8Parsing"
  322. // (the guess is based on the first 200 bytes of the file).
  323. FILE *f=_tfopen(filename,_T("rb"));
  324. if (f)
  325. {
  326. char bb[205];
  327. int l=(int)fread(bb,1,200,f);
  328. setGlobalOptions(guessUnicodeChars,guessUTF8ParsingParameterValue(bb,l),dropWhiteSpace);
  329. fclose(f);
  330. }
  331. // parse the file
  332. XMLResults pResults;
  333. XMLNode xnode=XMLNode::parseFile(filename,tag,&pResults);
  334. // display error message (if any)
  335. if (pResults.error != eXMLErrorNone)
  336. {
  337. // create message
  338. char message[2000],*s1=(char*)"",*s3=(char*)""; XMLCSTR s2=_T("");
  339. if (pResults.error==eXMLErrorFirstTagNotFound) { s1=(char*)"First Tag should be '"; s2=tag; s3=(char*)"'.\n"; }
  340. sprintf(message,
  341. #ifdef _XMLUNICODE
  342. "XML Parsing error inside file '%S'.\n%S\nAt line %i, column %i.\n%s%S%s"
  343. #else
  344. "XML Parsing error inside file '%s'.\n%s\nAt line %i, column %i.\n%s%s%s"
  345. #endif
  346. ,filename,XMLNode::getError(pResults.error),pResults.nLine,pResults.nColumn,s1,s2,s3);
  347. // display message
  348. #if defined(WIN32) && !defined(UNDER_CE) && !defined(_XMLPARSER_NO_MESSAGEBOX_)
  349. MessageBoxA(NULL,message,"XML Parsing error",MB_OK|MB_ICONERROR|MB_TOPMOST);
  350. #else
  351. printf("%s",message);
  352. #endif
  353. xnode = XMLNode::createXMLTopNode(tag);
  354. }
  355. return xnode;
  356. }
  357. #ifndef _XMLUNICODE
  358. // If "strictUTF8Parsing=0" then we assume that all characters have the same length of 1 byte.
  359. // If "strictUTF8Parsing=1" then the characters have different lengths (from 1 byte to 4 bytes).
  360. // This table is used as lookup-table to know the length of a character (in byte) based on the
  361. // content of the first byte of the character.
  362. // (note: if you modify this, you must always have XML_utf8ByteTable[0]=0 ).
  363. static const char XML_utf8ByteTable[256] =
  364. {
  365. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  366. 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
  367. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
  368. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
  369. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
  370. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
  371. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
  372. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
  373. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70End of ASCII range
  374. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 0x80 to 0xc1 invalid
  375. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
  376. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
  377. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
  378. 1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 0xc2 to 0xdf 2 byte
  379. 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
  380. 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,// 0xe0 0xe0 to 0xef 3 byte
  381. 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
  382. };
  383. static const char XML_asciiByteTable[256] =
  384. {
  385. 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,
  386. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  387. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  388. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  389. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  390. 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  391. };
  392. static const char *XML_ByteTable=(const char *)XML_utf8ByteTable; // the default is "strictUTF8Parsing=1"
  393. #endif
  394. XMLError XMLNode::writeToFile(XMLCSTR filename, const char *encoding, char nFormat) const
  395. {
  396. int i;
  397. XMLSTR t=createXMLString(nFormat,&i);
  398. FILE *f=_tfopen(filename,_T("wb"));
  399. if (!f) return eXMLErrorCannotOpenWriteFile;
  400. #ifdef _XMLUNICODE
  401. unsigned char h[2]={ 0xFF, 0xFE };
  402. if (!fwrite(h,2,1,f)) return eXMLErrorCannotWriteFile;
  403. if (!isDeclaration())
  404. {
  405. if (!fwrite(_T("<?xml version=\"1.0\" encoding=\"utf-16\"?>\n"),sizeof(wchar_t)*40,1,f))
  406. return eXMLErrorCannotWriteFile;
  407. }
  408. #else
  409. if (!isDeclaration())
  410. {
  411. if ((!encoding)||(XML_ByteTable==XML_utf8ByteTable))
  412. {
  413. // header so that windows recognize the file as UTF-8:
  414. unsigned char h[3]={0xEF,0xBB,0xBF};
  415. if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
  416. if (!fwrite("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",39,1,f)) return eXMLErrorCannotWriteFile;
  417. }
  418. else
  419. if (fprintf(f,"<?xml version=\"1.0\" encoding=\"%s\"?>\n",encoding)<0) return eXMLErrorCannotWriteFile;
  420. } else
  421. {
  422. if (XML_ByteTable==XML_utf8ByteTable) // test if strictUTF8Parsing==1"
  423. {
  424. unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
  425. }
  426. }
  427. #endif
  428. if (!fwrite(t,sizeof(XMLCHAR)*i,1,f)) return eXMLErrorCannotWriteFile;
  429. if (fclose(f)!=0) return eXMLErrorCannotWriteFile;
  430. free(t);
  431. return eXMLErrorNone;
  432. }
  433. // Duplicate a given string.
  434. XMLSTR stringDup(XMLCSTR lpszData, int cbData)
  435. {
  436. if (lpszData==NULL) return NULL;
  437. XMLSTR lpszNew;
  438. if (cbData==0) cbData=(int)_tcslen(lpszData);
  439. lpszNew = (XMLSTR)malloc((cbData+1) * sizeof(XMLCHAR));
  440. if (lpszNew)
  441. {
  442. memcpy(lpszNew, lpszData, (cbData) * sizeof(XMLCHAR));
  443. lpszNew[cbData] = (XMLCHAR)NULL;
  444. }
  445. return lpszNew;
  446. }
  447. XMLNode XMLNode::emptyXMLNode;
  448. XMLClear XMLNode::emptyXMLClear={ NULL, NULL, NULL};
  449. XMLAttribute XMLNode::emptyXMLAttribute={ NULL, NULL};
  450. // Enumeration used to decipher what type a token is
  451. typedef enum XMLTokenTypeTag
  452. {
  453. eTokenText = 0,
  454. eTokenQuotedText,
  455. eTokenTagStart, /* "<" */
  456. eTokenTagEnd, /* "</" */
  457. eTokenCloseTag, /* ">" */
  458. eTokenEquals, /* "=" */
  459. eTokenDeclaration, /* "<?" */
  460. eTokenShortHandClose, /* "/>" */
  461. eTokenClear,
  462. eTokenError
  463. } XMLTokenType;
  464. // Main structure used for parsing XML
  465. typedef struct XML
  466. {
  467. XMLCSTR lpXML;
  468. XMLCSTR lpszText;
  469. int nIndex,nIndexMissigEndTag;
  470. enum XMLError error;
  471. XMLCSTR lpEndTag;
  472. int cbEndTag;
  473. XMLCSTR lpNewElement;
  474. int cbNewElement;
  475. int nFirst;
  476. } XML;
  477. typedef struct
  478. {
  479. ALLXMLClearTag *pClr;
  480. XMLCSTR pStr;
  481. } NextToken;
  482. // Enumeration used when parsing attributes
  483. typedef enum Attrib
  484. {
  485. eAttribName = 0,
  486. eAttribEquals,
  487. eAttribValue
  488. } Attrib;
  489. // Enumeration used when parsing elements to dictate whether we are currently
  490. // inside a tag
  491. typedef enum Status
  492. {
  493. eInsideTag = 0,
  494. eOutsideTag
  495. } Status;
  496. // private (used while rendering):
  497. XMLSTR toXMLString(XMLSTR dest,XMLCSTR source)
  498. {
  499. XMLSTR dd=dest;
  500. XMLCHAR ch;
  501. XMLCharacterEntity *entity;
  502. while ((ch=*source))
  503. {
  504. entity=XMLEntities;
  505. do
  506. {
  507. if (ch==entity->c) {_tcscpy(dest,entity->s); dest+=entity->l; source++; goto out_of_loop1; }
  508. entity++;
  509. } while(entity->s);
  510. #ifdef _XMLUNICODE
  511. *(dest++)=*(source++);
  512. #else
  513. switch(XML_ByteTable[(unsigned char)ch])
  514. {
  515. case 4: *(dest++)=*(source++);
  516. case 3: *(dest++)=*(source++);
  517. case 2: *(dest++)=*(source++);
  518. case 1: *(dest++)=*(source++);
  519. }
  520. #endif
  521. out_of_loop1:
  522. ;
  523. }
  524. *dest=0;
  525. return dd;
  526. }
  527. // private (used while rendering):
  528. int lengthXMLString(XMLCSTR source)
  529. {
  530. int r=0;
  531. XMLCharacterEntity *entity;
  532. XMLCHAR ch;
  533. while ((ch=*source))
  534. {
  535. entity=XMLEntities;
  536. do
  537. {
  538. if (ch==entity->c) { r+=entity->l; source++; goto out_of_loop1; }
  539. entity++;
  540. } while(entity->s);
  541. #ifdef _XMLUNICODE
  542. r++; source++;
  543. #else
  544. ch=XML_ByteTable[(unsigned char)ch]; r+=ch; source+=ch;
  545. #endif
  546. out_of_loop1:
  547. ;
  548. }
  549. return r;
  550. }
  551. XMLSTR toXMLString(XMLCSTR source)
  552. {
  553. XMLSTR dest=(XMLSTR)malloc((lengthXMLString(source)+1)*sizeof(XMLCHAR));
  554. return toXMLString(dest,source);
  555. }
  556. XMLSTR toXMLStringFast(XMLSTR *dest,int *destSz, XMLCSTR source)
  557. {
  558. int l=lengthXMLString(source)+1;
  559. if (l>*destSz) { *destSz=l; *dest=(XMLSTR)realloc(*dest,l*sizeof(XMLCHAR)); }
  560. return toXMLString(*dest,source);
  561. }
  562. // private:
  563. XMLSTR fromXMLString(XMLCSTR s, int lo, XML *pXML)
  564. {
  565. // This function is the opposite of the function "toXMLString". It decodes the escape
  566. // sequences &amp;, &quot;, &apos;, &lt;, &gt; and replace them by the characters
  567. // &,",',<,>. This function is used internally by the XML Parser. All the calls to
  568. // the XML library will always gives you back "decoded" strings.
  569. //
  570. // in: string (s) and length (lo) of string
  571. // out: new allocated string converted from xml
  572. if (!s) return NULL;
  573. int ll=0,j;
  574. XMLSTR d;
  575. XMLCSTR ss=s;
  576. XMLCharacterEntity *entity;
  577. while ((lo>0)&&(*s))
  578. {
  579. if (*s==_T('&'))
  580. {
  581. if ((lo>2)&&(s[1]==_T('#')))
  582. {
  583. s+=2; lo-=2;
  584. if ((*s==_T('X'))||(*s==_T('x'))) { s++; lo--; }
  585. while ((*s)&&(*s!=_T(';'))&&((lo--)>0)) s++;
  586. if (*s!=_T(';'))
  587. {
  588. pXML->error=eXMLErrorUnknownCharacterEntity;
  589. return NULL;
  590. }
  591. s++; lo--;
  592. } else
  593. {
  594. entity=XMLEntities;
  595. do
  596. {
  597. if ((lo>=entity->l)&&(_tcsnicmp(s,entity->s,entity->l)==0)) { s+=entity->l; lo-=entity->l; break; }
  598. entity++;
  599. } while(entity->s);
  600. if (!entity->s)
  601. {
  602. pXML->error=eXMLErrorUnknownCharacterEntity;
  603. return NULL;
  604. }
  605. }
  606. } else
  607. {
  608. #ifdef _XMLUNICODE
  609. s++; lo--;
  610. #else
  611. j=XML_ByteTable[(unsigned char)*s]; s+=j; lo-=j; ll+=j-1;
  612. #endif
  613. }
  614. ll++;
  615. }
  616. d=(XMLSTR)malloc((ll+1)*sizeof(XMLCHAR));
  617. s=d;
  618. while (ll-->0)
  619. {
  620. if (*ss==_T('&'))
  621. {
  622. if (ss[1]==_T('#'))
  623. {
  624. ss+=2; j=0;
  625. if ((*ss==_T('X'))||(*ss==_T('x')))
  626. {
  627. ss++;
  628. while (*ss!=_T(';'))
  629. {
  630. if ((*ss>=_T('0'))&&(*ss<=_T('9'))) j=(j<<4)+*ss-_T('0');
  631. else if ((*ss>=_T('A'))&&(*ss<=_T('F'))) j=(j<<4)+*ss-_T('A')+10;
  632. else if ((*ss>=_T('a'))&&(*ss<=_T('f'))) j=(j<<4)+*ss-_T('a')+10;
  633. else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
  634. ss++;
  635. }
  636. } else
  637. {
  638. while (*ss!=_T(';'))
  639. {
  640. if ((*ss>=_T('0'))&&(*ss<=_T('9'))) j=(j*10)+*ss-_T('0');
  641. else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
  642. ss++;
  643. }
  644. }
  645. (*d++)=(XMLCHAR)j; ss++;
  646. } else
  647. {
  648. entity=XMLEntities;
  649. do
  650. {
  651. if (_tcsnicmp(ss,entity->s,entity->l)==0) { *(d++)=entity->c; ss+=entity->l; break; }
  652. entity++;
  653. } while(entity->s);
  654. }
  655. } else
  656. {
  657. #ifdef _XMLUNICODE
  658. *(d++)=*(ss++);
  659. #else
  660. switch(XML_ByteTable[(unsigned char)*ss])
  661. {
  662. case 4: *(d++)=*(ss++); ll--;
  663. case 3: *(d++)=*(ss++); ll--;
  664. case 2: *(d++)=*(ss++); ll--;
  665. case 1: *(d++)=*(ss++);
  666. }
  667. #endif
  668. }
  669. }
  670. *d=0;
  671. return (XMLSTR)s;
  672. }
  673. #define XML_isSPACECHAR(ch) ((ch==_T('\n'))||(ch==_T(' '))||(ch== _T('\t'))||(ch==_T('\r')))
  674. // private:
  675. char myTagCompare(XMLCSTR cclose, XMLCSTR copen)
  676. // !!!! WARNING strange convention&:
  677. // return 0 if equals
  678. // return 1 if different
  679. {
  680. if (!cclose) return 1;
  681. int l=(int)_tcslen(cclose);
  682. if (_tcsnicmp(cclose, copen, l)!=0) return 1;
  683. const XMLCHAR c=copen[l];
  684. if (XML_isSPACECHAR(c)||
  685. (c==_T('/' ))||
  686. (c==_T('<' ))||
  687. (c==_T('>' ))||
  688. (c==_T('=' ))) return 0;
  689. return 1;
  690. }
  691. // Obtain the next character from the string.
  692. static inline XMLCHAR getNextChar(XML *pXML)
  693. {
  694. XMLCHAR ch = pXML->lpXML[pXML->nIndex];
  695. #ifdef _XMLUNICODE
  696. if (ch!=0) pXML->nIndex++;
  697. #else
  698. pXML->nIndex+=XML_ByteTable[(unsigned char)ch];
  699. #endif
  700. return ch;
  701. }
  702. // Find the next token in a string.
  703. // pcbToken contains the number of characters that have been read.
  704. static NextToken GetNextToken(XML *pXML, int *pcbToken, enum XMLTokenTypeTag *pType)
  705. {
  706. NextToken result;
  707. XMLCHAR ch;
  708. XMLCHAR chTemp;
  709. int indexStart,nFoundMatch,nIsText=FALSE;
  710. result.pClr=NULL; // prevent warning
  711. // Find next non-white space character
  712. do { indexStart=pXML->nIndex; ch=getNextChar(pXML); } while XML_isSPACECHAR(ch);
  713. if (ch)
  714. {
  715. // Cache the current string pointer
  716. result.pStr = &pXML->lpXML[indexStart];
  717. // First check whether the token is in the clear tag list (meaning it
  718. // does not need formatting).
  719. ALLXMLClearTag *ctag=XMLClearTags;
  720. do
  721. {
  722. if (_tcsnicmp(ctag->lpszOpen, result.pStr, ctag->openTagLen)==0)
  723. {
  724. result.pClr=ctag;
  725. pXML->nIndex+=ctag->openTagLen-1;
  726. *pType=eTokenClear;
  727. return result;
  728. }
  729. ctag++;
  730. } while(ctag->lpszOpen);
  731. // If we didn't find a clear tag then check for standard tokens
  732. switch(ch)
  733. {
  734. // Check for quotes
  735. case _T('\''):
  736. case _T('\"'):
  737. // Type of token
  738. *pType = eTokenQuotedText;
  739. chTemp = ch;
  740. // Set the size
  741. nFoundMatch = FALSE;
  742. // Search through the string to find a matching quote
  743. while((ch = getNextChar(pXML)))
  744. {
  745. if (ch==chTemp) { nFoundMatch = TRUE; break; }
  746. if (ch==_T('<')) break;
  747. }
  748. // If we failed to find a matching quote
  749. if (nFoundMatch == FALSE)
  750. {
  751. pXML->nIndex=indexStart+1;
  752. nIsText=TRUE;
  753. break;
  754. }
  755. // 4.02.2002
  756. // if (FindNonWhiteSpace(pXML)) pXML->nIndex--;
  757. break;
  758. // Equals (used with attribute values)
  759. case _T('='):
  760. *pType = eTokenEquals;
  761. break;
  762. // Close tag
  763. case _T('>'):
  764. *pType = eTokenCloseTag;
  765. break;
  766. // Check for tag start and tag end
  767. case _T('<'):
  768. // Peek at the next character to see if we have an end tag '</',
  769. // or an xml declaration '<?'
  770. chTemp = pXML->lpXML[pXML->nIndex];
  771. // If we have a tag end...
  772. if (chTemp == _T('/'))
  773. {
  774. // Set the type and ensure we point at the next character
  775. getNextChar(pXML);
  776. *pType = eTokenTagEnd;
  777. }
  778. // If we have an XML declaration tag
  779. else if (chTemp == _T('?'))
  780. {
  781. // Set the type and ensure we point at the next character
  782. getNextChar(pXML);
  783. *pType = eTokenDeclaration;
  784. }
  785. // Otherwise we must have a start tag
  786. else
  787. {
  788. *pType = eTokenTagStart;
  789. }
  790. break;
  791. // Check to see if we have a short hand type end tag ('/>').
  792. case _T('/'):
  793. // Peek at the next character to see if we have a short end tag '/>'
  794. chTemp = pXML->lpXML[pXML->nIndex];
  795. // If we have a short hand end tag...
  796. if (chTemp == _T('>'))
  797. {
  798. // Set the type and ensure we point at the next character
  799. getNextChar(pXML);
  800. *pType = eTokenShortHandClose;
  801. break;
  802. }
  803. // If we haven't found a short hand closing tag then drop into the
  804. // text process
  805. // Other characters
  806. default:
  807. nIsText = TRUE;
  808. }
  809. // If this is a TEXT node
  810. if (nIsText)
  811. {
  812. // Indicate we are dealing with text
  813. *pType = eTokenText;
  814. while((ch = getNextChar(pXML)))
  815. {
  816. if XML_isSPACECHAR(ch)
  817. {
  818. indexStart++; break;
  819. } else if (ch==_T('/'))
  820. {
  821. // If we find a slash then this maybe text or a short hand end tag
  822. // Peek at the next character to see it we have short hand end tag
  823. ch=pXML->lpXML[pXML->nIndex];
  824. // If we found a short hand end tag then we need to exit the loop
  825. if (ch==_T('>')) { pXML->nIndex--; break; }
  826. } else if ((ch==_T('<'))||(ch==_T('>'))||(ch==_T('=')))
  827. {
  828. pXML->nIndex--; break;
  829. }
  830. }
  831. }
  832. *pcbToken = pXML->nIndex-indexStart;
  833. } else
  834. {
  835. // If we failed to obtain a valid character
  836. *pcbToken = 0;
  837. *pType = eTokenError;
  838. result.pStr=NULL;
  839. }
  840. return result;
  841. }
  842. XMLCSTR XMLNode::updateName_WOSD(XMLCSTR lpszName)
  843. {
  844. if (d->lpszName&&(lpszName!=d->lpszName)) free((void*)d->lpszName);
  845. d->lpszName=lpszName;
  846. return lpszName;
  847. }
  848. // private:
  849. XMLNode::XMLNode(struct XMLNodeDataTag *p){ d=p; (p->ref_count)++; }
  850. XMLNode::XMLNode(XMLNodeData *pParent, XMLCSTR lpszName, char isDeclaration)
  851. {
  852. d=(XMLNodeData*)malloc(sizeof(XMLNodeData));
  853. d->ref_count=1;
  854. d->lpszName=NULL;
  855. d->nChild= 0;
  856. d->nText = 0;
  857. d->nClear = 0;
  858. d->nAttribute = 0;
  859. d->isDeclaration = isDeclaration;
  860. d->pParent = pParent;
  861. d->pChild= NULL;
  862. d->pText= NULL;
  863. d->pClear= NULL;
  864. d->pAttribute= NULL;
  865. d->pOrder= NULL;
  866. updateName_WOSD(lpszName);
  867. }
  868. XMLNode XMLNode::createXMLTopNode_WOSD(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,lpszName,isDeclaration); }
  869. XMLNode XMLNode::createXMLTopNode(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,stringDup(lpszName),isDeclaration); }
  870. #define MEMORYINCREASE 50
  871. static inline void *myRealloc(void *p, int newsize, int memInc, int sizeofElem)
  872. {
  873. if (p==NULL) { if (memInc) return malloc(memInc*sizeofElem); return malloc(sizeofElem); }
  874. if ((memInc==0)||((newsize%memInc)==0)) p=realloc(p,(newsize+memInc)*sizeofElem);
  875. // if (!p)
  876. // {
  877. // printf("XMLParser Error: Not enough memory! Aborting...\n"); exit(220);
  878. // }
  879. return p;
  880. }
  881. // private:
  882. int XMLNode::findPosition(XMLNodeData *d, int index, XMLElementType xtype)
  883. {
  884. if (index<0) return -1;
  885. int i=0,j=(int)((index<<2)+xtype),*o=d->pOrder; while (o[i]!=j) i++; return i;
  886. }
  887. // private:
  888. // update "order" information when deleting a content of a XMLNode
  889. int XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index)
  890. {
  891. int n=d->nChild+d->nText+d->nClear, *o=d->pOrder,i=findPosition(d,index,t);
  892. memmove(o+i, o+i+1, (n-i)*sizeof(int));
  893. for (;i<n;i++)
  894. if ((o[i]&3)==(int)t) o[i]-=4;
  895. // We should normally do:
  896. // d->pOrder=(int)realloc(d->pOrder,n*sizeof(int));
  897. // but we skip reallocation because it's too time consuming.
  898. // Anyway, at the end, it will be free'd completely at once.
  899. return i;
  900. }
  901. void *XMLNode::addToOrder(int memoryIncrease,int *_pos, int nc, void *p, int size, XMLElementType xtype)
  902. {
  903. // in: *_pos is the position inside d->pOrder ("-1" means "EndOf")
  904. // out: *_pos is the index inside p
  905. p=myRealloc(p,(nc+1),memoryIncrease,size);
  906. int n=d->nChild+d->nText+d->nClear;
  907. d->pOrder=(int*)myRealloc(d->pOrder,n+1,memoryIncrease*3,sizeof(int));
  908. int pos=*_pos,*o=d->pOrder;
  909. if ((pos<0)||(pos>=n)) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
  910. int i=pos;
  911. memmove(o+i+1, o+i, (n-i)*sizeof(int));
  912. while ((pos<n)&&((o[pos]&3)!=(int)xtype)) pos++;
  913. if (pos==n) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
  914. o[i]=o[pos];
  915. for (i=pos+1;i<=n;i++) if ((o[i]&3)==(int)xtype) o[i]+=4;
  916. *_pos=pos=o[pos]>>2;
  917. memmove(((char*)p)+(pos+1)*size,((char*)p)+pos*size,(nc-pos)*size);
  918. return p;
  919. }
  920. // Add a child node to the given element.
  921. XMLNode XMLNode::addChild_priv(int memoryIncrease, XMLCSTR lpszName, char isDeclaration, int pos)
  922. {
  923. if (!lpszName) return emptyXMLNode;
  924. d->pChild=(XMLNode*)addToOrder(memoryIncrease,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
  925. d->pChild[pos].d=NULL;
  926. d->pChild[pos]=XMLNode(d,lpszName,isDeclaration);
  927. d->nChild++;
  928. return d->pChild[pos];
  929. }
  930. // Add an attribute to an element.
  931. XMLAttribute *XMLNode::addAttribute_priv(int memoryIncrease,XMLCSTR lpszName, XMLCSTR lpszValuev)
  932. {
  933. if (!lpszName) return &emptyXMLAttribute;
  934. int nc=d->nAttribute;
  935. d->pAttribute=(XMLAttribute*)myRealloc(d->pAttribute,(nc+1),memoryIncrease,sizeof(XMLAttribute));
  936. XMLAttribute *pAttr=d->pAttribute+nc;
  937. pAttr->lpszName = lpszName;
  938. pAttr->lpszValue = lpszValuev;
  939. d->nAttribute++;
  940. return pAttr;
  941. }
  942. // Add text to the element.
  943. XMLCSTR XMLNode::addText_priv(int memoryIncrease, XMLCSTR lpszValue, int pos)
  944. {
  945. if (!lpszValue) return NULL;
  946. d->pText=(XMLCSTR*)addToOrder(memoryIncrease,&pos,d->nText,d->pText,sizeof(XMLSTR),eNodeText);
  947. d->pText[pos]=lpszValue;
  948. d->nText++;
  949. return lpszValue;
  950. }
  951. // Add clear (unformatted) text to the element.
  952. XMLClear *XMLNode::addClear_priv(int memoryIncrease, XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
  953. {
  954. if (!lpszValue) return &emptyXMLClear;
  955. d->pClear=(XMLClear *)addToOrder(memoryIncrease,&pos,d->nClear,d->pClear,sizeof(XMLClear),eNodeClear);
  956. XMLClear *pNewClear=d->pClear+pos;
  957. pNewClear->lpszValue = lpszValue;
  958. if (!lpszOpen) lpszOpen=getClearTagTable()->lpszOpen;
  959. if (!lpszClose) lpszOpen=getClearTagTable()->lpszClose;
  960. pNewClear->lpszOpenTag = lpszOpen;
  961. pNewClear->lpszCloseTag = lpszClose;
  962. d->nClear++;
  963. return pNewClear;
  964. }
  965. // private:
  966. // Parse a clear (unformatted) type node.
  967. char XMLNode::parseClearTag(void *px, ALLXMLClearTag *pClear)
  968. {
  969. XML *pXML=(XML *)px;
  970. int cbTemp=0;
  971. XMLCSTR lpszTemp=NULL;
  972. XMLCSTR lpXML=&pXML->lpXML[pXML->nIndex];
  973. static XMLCSTR docTypeEnd=_T("]>");
  974. // Find the closing tag
  975. // Seems the <!DOCTYPE need a better treatment so lets handle it
  976. if (pClear->lpszOpen==XMLClearTags[1].lpszOpen)
  977. {
  978. XMLCSTR pCh=lpXML;
  979. while (*pCh)
  980. {
  981. if (*pCh==_T('<')) { pClear->lpszClose=docTypeEnd; lpszTemp=_tcsstr(lpXML,docTypeEnd); break; }
  982. else if (*pCh==_T('>')) { lpszTemp=pCh; break; }
  983. #ifdef _XMLUNICODE
  984. pCh++;
  985. #else
  986. pCh+=XML_ByteTable[(unsigned char)(*pCh)];
  987. #endif
  988. }
  989. } else lpszTemp=_tcsstr(lpXML, pClear->lpszClose);
  990. if (lpszTemp)
  991. {
  992. // Cache the size and increment the index
  993. cbTemp = (int)(lpszTemp - lpXML);
  994. pXML->nIndex += cbTemp+(int)_tcslen(pClear->lpszClose);
  995. // Add the clear node to the current element
  996. addClear_priv(MEMORYINCREASE,stringDup(lpXML,cbTemp), pClear->lpszOpen, pClear->lpszClose,-1);
  997. return 0;
  998. }
  999. // If we failed to find the end tag
  1000. pXML->error = eXMLErrorUnmatchedEndClearTag;
  1001. return 1;
  1002. }
  1003. void XMLNode::exactMemory(XMLNodeData *d)
  1004. {
  1005. if (d->pOrder) d->pOrder=(int*)realloc(d->pOrder,(d->nChild+d->nText+d->nClear)*sizeof(int));
  1006. if (d->pChild) d->pChild=(XMLNode*)realloc(d->pChild,d->nChild*sizeof(XMLNode));
  1007. if (d->pAttribute) d->pAttribute=(XMLAttribute*)realloc(d->pAttribute,d->nAttribute*sizeof(XMLAttribute));
  1008. if (d->pText) d->pText=(XMLCSTR*)realloc(d->pText,d->nText*sizeof(XMLSTR));
  1009. if (d->pClear) d->pClear=(XMLClear *)realloc(d->pClear,d->nClear*sizeof(XMLClear));
  1010. }
  1011. char XMLNode::maybeAddTxT(void *pa, XMLCSTR tokenPStr)
  1012. {
  1013. XML *pXML=(XML *)pa;
  1014. XMLCSTR lpszText=pXML->lpszText;
  1015. if (!lpszText) return 0;
  1016. if (dropWhiteSpace) while (XML_isSPACECHAR(*lpszText)&&(lpszText!=tokenPStr)) lpszText++;
  1017. int cbText = (int)(tokenPStr - lpszText);
  1018. if (!cbText) { pXML->lpszText=NULL; return 0; }
  1019. if (dropWhiteSpace) { cbText--; while ((cbText)&&XML_isSPACECHAR(lpszText[cbText])) cbText--; cbText++; }
  1020. if (!cbText) { pXML->lpszText=NULL; return 0; }
  1021. lpszText=fromXMLString(lpszText,cbText,pXML);
  1022. if (!lpszText) return 1;
  1023. addText_priv(MEMORYINCREASE,lpszText,-1);
  1024. pXML->lpszText=NULL;
  1025. return 0;
  1026. }
  1027. // private:
  1028. // Recursively parse an XML element.
  1029. int XMLNode::ParseXMLElement(void *pa)
  1030. {
  1031. XML *pXML=(XML *)pa;
  1032. int cbToken;
  1033. enum XMLTokenTypeTag type;
  1034. NextToken token;
  1035. XMLCSTR lpszTemp=NULL;
  1036. int cbTemp=0;
  1037. char nDeclaration;
  1038. XMLNode pNew;
  1039. enum Status status; // inside or outside a tag
  1040. enum Attrib attrib = eAttribName;
  1041. assert(pXML);
  1042. // If this is the first call to the function
  1043. if (pXML->nFirst)
  1044. {
  1045. // Assume we are outside of a tag definition
  1046. pXML->nFirst = FALSE;
  1047. status = eOutsideTag;
  1048. } else
  1049. {
  1050. // If this is not the first call then we should only be called when inside a tag.
  1051. status = eInsideTag;
  1052. }
  1053. // Iterate through the tokens in the document
  1054. for(;;)
  1055. {
  1056. // Obtain the next token
  1057. token = GetNextToken(pXML, &cbToken, &type);
  1058. if (type != eTokenError)
  1059. {
  1060. // Check the current status
  1061. switch(status)
  1062. {
  1063. // If we are outside of a tag definition
  1064. case eOutsideTag:
  1065. // Check what type of token we obtained
  1066. switch(type)
  1067. {
  1068. // If we have found text or quoted text
  1069. case eTokenText:
  1070. case eTokenCloseTag: /* '>' */
  1071. case eTokenShortHandClose: /* '/>' */
  1072. case eTokenQuotedText:
  1073. case eTokenEquals:
  1074. break;
  1075. // If we found a start tag '<' and declarations '<?'
  1076. case eTokenTagStart:
  1077. case eTokenDeclaration:
  1078. // Cache whether this new element is a declaration or not
  1079. nDeclaration = (type == eTokenDeclaration);
  1080. // If we have node text then add this to the element
  1081. if (maybeAddTxT(pXML,token.pStr)) return FALSE;
  1082. // Find the name of the tag
  1083. token = GetNextToken(pXML, &cbToken, &type);
  1084. // Return an error if we couldn't obtain the next token or
  1085. // it wasnt text
  1086. if (type != eTokenText)
  1087. {
  1088. pXML->error = eXMLErrorMissingTagName;
  1089. return FALSE;
  1090. }
  1091. // If we found a new element which is the same as this
  1092. // element then we need to pass this back to the caller..
  1093. #ifdef APPROXIMATE_PARSING
  1094. if (d->lpszName &&
  1095. myTagCompare(d->lpszName, token.pStr) == 0)
  1096. {
  1097. // Indicate to the caller that it needs to create a
  1098. // new element.
  1099. pXML->lpNewElement = token.pStr;
  1100. pXML->cbNewElement = cbToken;
  1101. return TRUE;
  1102. } else
  1103. #endif
  1104. {
  1105. // If the name of the new element differs from the name of
  1106. // the current element we need to add the new element to
  1107. // the current one and recurse
  1108. pNew = addChild_priv(MEMORYINCREASE,stringDup(token.pStr,cbToken), nDeclaration,-1);
  1109. while (!pNew.isEmpty())
  1110. {
  1111. // Callself to process the new node. If we return
  1112. // FALSE this means we dont have any more
  1113. // processing to do...
  1114. if (!pNew.ParseXMLElement(pXML)) return FALSE;
  1115. else
  1116. {
  1117. // If the call to recurse this function
  1118. // evented in a end tag specified in XML then
  1119. // we need to unwind the calls to this
  1120. // function until we find the appropriate node
  1121. // (the element name and end tag name must
  1122. // match)
  1123. if (pXML->cbEndTag)
  1124. {
  1125. // If we are back at the root node then we
  1126. // have an unmatched end tag
  1127. if (!d->lpszName)
  1128. {
  1129. pXML->error=eXMLErrorUnmatchedEndTag;
  1130. return FALSE;
  1131. }
  1132. // If the end tag matches the name of this
  1133. // element then we only need to unwind
  1134. // once more...
  1135. if (myTagCompare(d->lpszName, pXML->lpEndTag)==0)
  1136. {
  1137. pXML->cbEndTag = 0;
  1138. }
  1139. return TRUE;
  1140. } else
  1141. if (pXML->cbNewElement)
  1142. {
  1143. // If the call indicated a new element is to
  1144. // be created on THIS element.
  1145. // If the name of this element matches the
  1146. // name of the element we need to create
  1147. // then we need to return to the caller
  1148. // and let it process the element.
  1149. if (myTagCompare(d->lpszName, pXML->lpNewElement)==0)
  1150. {
  1151. return TRUE;

Large files files are truncated, but you can click here to view the full file