PageRenderTime 67ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/Horde3D/Source/Shared/utXMLParser.cpp

https://bitbucket.org/sanyaade/horde3dext
C++ | 2729 lines | 2127 code | 227 blank | 375 comment | 433 complexity | ce824b1f113317323ba7b267e76d1f65 MD5 | raw file

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

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

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