PageRenderTime 72ms CodeModel.GetById 20ms 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
  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;
  1152. }
  1153. // Add the new element and recurse
  1154. pNew = addChild_priv(MEMORYINCREASE,stringDup(pXML->lpNewElement,pXML->cbNewElement),0,-1);
  1155. pXML->cbNewElement = 0;
  1156. }
  1157. else
  1158. {
  1159. // If we didn't have a new element to create
  1160. pNew = emptyXMLNode;
  1161. }
  1162. }
  1163. }
  1164. }
  1165. break;
  1166. // If we found an end tag
  1167. case eTokenTagEnd:
  1168. // If we have node text then add this to the element
  1169. if (maybeAddTxT(pXML,token.pStr)) return FALSE;
  1170. // Find the name of the end tag
  1171. token = GetNextToken(pXML, &cbTemp, &type);
  1172. // The end tag should be text
  1173. if (type != eTokenText)
  1174. {
  1175. pXML->error = eXMLErrorMissingEndTagName;
  1176. return FALSE;
  1177. }
  1178. lpszTemp = token.pStr;
  1179. // After the end tag we should find a closing tag
  1180. token = GetNextToken(pXML, &cbToken, &type);
  1181. if (type != eTokenCloseTag)
  1182. {
  1183. pXML->error = eXMLErrorMissingEndTagName;
  1184. return FALSE;
  1185. }
  1186. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1187. // We need to return to the previous caller. If the name
  1188. // of the tag cannot be found we need to keep returning to
  1189. // caller until we find a match
  1190. if (myTagCompare(d->lpszName, lpszTemp) != 0)
  1191. #ifdef STRICT_PARSING
  1192. {
  1193. pXML->error=eXMLErrorUnmatchedEndTag;
  1194. pXML->nIndexMissigEndTag=pXML->nIndex;
  1195. return FALSE;
  1196. }
  1197. #else
  1198. {
  1199. pXML->error=eXMLErrorMissingEndTag;
  1200. pXML->nIndexMissigEndTag=pXML->nIndex;
  1201. pXML->lpEndTag = lpszTemp;
  1202. pXML->cbEndTag = cbTemp;
  1203. }
  1204. #endif
  1205. // Return to the caller
  1206. exactMemory(d);
  1207. return TRUE;
  1208. // If we found a clear (unformatted) token
  1209. case eTokenClear:
  1210. // If we have node text then add this to the element
  1211. if (maybeAddTxT(pXML,token.pStr)) return FALSE;
  1212. if (parseClearTag(pXML, token.pClr)) return FALSE;
  1213. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1214. break;
  1215. default:
  1216. break;
  1217. }
  1218. break;
  1219. // If we are inside a tag definition we need to search for attributes
  1220. case eInsideTag:
  1221. // Check what part of the attribute (name, equals, value) we
  1222. // are looking for.
  1223. switch(attrib)
  1224. {
  1225. // If we are looking for a new attribute
  1226. case eAttribName:
  1227. // Check what the current token type is
  1228. switch(type)
  1229. {
  1230. // If the current type is text...
  1231. // Eg. 'attribute'
  1232. case eTokenText:
  1233. // Cache the token then indicate that we are next to
  1234. // look for the equals
  1235. lpszTemp = token.pStr;
  1236. cbTemp = cbToken;
  1237. attrib = eAttribEquals;
  1238. break;
  1239. // If we found a closing tag...
  1240. // Eg. '>'
  1241. case eTokenCloseTag:
  1242. // We are now outside the tag
  1243. status = eOutsideTag;
  1244. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1245. break;
  1246. // If we found a short hand '/>' closing tag then we can
  1247. // return to the caller
  1248. case eTokenShortHandClose:
  1249. exactMemory(d);
  1250. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1251. return TRUE;
  1252. // Errors...
  1253. case eTokenQuotedText: /* '"SomeText"' */
  1254. case eTokenTagStart: /* '<' */
  1255. case eTokenTagEnd: /* '</' */
  1256. case eTokenEquals: /* '=' */
  1257. case eTokenDeclaration: /* '<?' */
  1258. case eTokenClear:
  1259. pXML->error = eXMLErrorUnexpectedToken;
  1260. return FALSE;
  1261. default: break;
  1262. }
  1263. break;
  1264. // If we are looking for an equals
  1265. case eAttribEquals:
  1266. // Check what the current token type is
  1267. switch(type)
  1268. {
  1269. // If the current type is text...
  1270. // Eg. 'Attribute AnotherAttribute'
  1271. case eTokenText:
  1272. // Add the unvalued attribute to the list
  1273. addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
  1274. // Cache the token then indicate. We are next to
  1275. // look for the equals attribute
  1276. lpszTemp = token.pStr;
  1277. cbTemp = cbToken;
  1278. break;
  1279. // If we found a closing tag 'Attribute >' or a short hand
  1280. // closing tag 'Attribute />'
  1281. case eTokenShortHandClose:
  1282. case eTokenCloseTag:
  1283. // If we are a declaration element '<?' then we need
  1284. // to remove extra closing '?' if it exists
  1285. pXML->lpszText=pXML->lpXML+pXML->nIndex;
  1286. if (d->isDeclaration &&
  1287. (lpszTemp[cbTemp-1]) == _T('?'))
  1288. {
  1289. cbTemp--;
  1290. }
  1291. if (cbTemp)
  1292. {
  1293. // Add the unvalued attribute to the list
  1294. addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
  1295. }
  1296. // If this is the end of the tag then return to the caller
  1297. if (type == eTokenShortHandClose)
  1298. {
  1299. exactMemory(d);
  1300. return TRUE;
  1301. }
  1302. // We are now outside the tag
  1303. status = eOutsideTag;
  1304. break;
  1305. // If we found the equals token...
  1306. // Eg. 'Attribute ='
  1307. case eTokenEquals:
  1308. // Indicate that we next need to search for the value
  1309. // for the attribute
  1310. attrib = eAttribValue;
  1311. break;
  1312. // Errors...
  1313. case eTokenQuotedText: /* 'Attribute "InvalidAttr"'*/
  1314. case eTokenTagStart: /* 'Attribute <' */
  1315. case eTokenTagEnd: /* 'Attribute </' */
  1316. case eTokenDeclaration: /* 'Attribute <?' */
  1317. case eTokenClear:
  1318. pXML->error = eXMLErrorUnexpectedToken;
  1319. return FALSE;
  1320. default: break;
  1321. }
  1322. break;
  1323. // If we are looking for an attribute value
  1324. case eAttribValue:
  1325. // Check what the current token type is
  1326. switch(type)
  1327. {
  1328. // If the current type is text or quoted text...
  1329. // Eg. 'Attribute = "Value"' or 'Attribute = Value' or
  1330. // 'Attribute = 'Value''.
  1331. case eTokenText:
  1332. case eTokenQuotedText:
  1333. // If we are a declaration element '<?' then we need
  1334. // to remove extra closing '?' if it exists
  1335. if (d->isDeclaration &&
  1336. (token.pStr[cbToken-1]) == _T('?'))
  1337. {
  1338. cbToken--;
  1339. }
  1340. if (cbTemp)
  1341. {
  1342. // Add the valued attribute to the list
  1343. if (type==eTokenQuotedText) { token.pStr++; cbToken-=2; }
  1344. XMLCSTR attrVal=token.pStr;
  1345. if (attrVal)
  1346. {
  1347. attrVal=fromXMLString(attrVal,cbToken,pXML);
  1348. if (!attrVal) return FALSE;
  1349. }
  1350. addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp),attrVal);
  1351. }
  1352. // Indicate we are searching for a new attribute
  1353. attrib = eAttribName;
  1354. break;
  1355. // Errors...
  1356. case eTokenTagStart: /* 'Attr = <' */
  1357. case eTokenTagEnd: /* 'Attr = </' */
  1358. case eTokenCloseTag: /* 'Attr = >' */
  1359. case eTokenShortHandClose: /* "Attr = />" */
  1360. case eTokenEquals: /* 'Attr = =' */
  1361. case eTokenDeclaration: /* 'Attr = <?' */
  1362. case eTokenClear:
  1363. pXML->error = eXMLErrorUnexpectedToken;
  1364. return FALSE;
  1365. break;
  1366. default: break;
  1367. }
  1368. }
  1369. }
  1370. }
  1371. // If we failed to obtain the next token
  1372. else
  1373. {
  1374. if ((!d->isDeclaration)&&(d->pParent))
  1375. {
  1376. #ifdef STRICT_PARSING
  1377. pXML->error=eXMLErrorUnmatchedEndTag;
  1378. #else
  1379. pXML->error=eXMLErrorMissingEndTag;
  1380. #endif
  1381. pXML->nIndexMissigEndTag=pXML->nIndex;
  1382. }
  1383. return FALSE;
  1384. }
  1385. }
  1386. }
  1387. // Count the number of lines and columns in an XML string.
  1388. static void CountLinesAndColumns(XMLCSTR lpXML, int nUpto, XMLResults *pResults)
  1389. {
  1390. XMLCHAR ch;
  1391. assert(lpXML);
  1392. assert(pResults);
  1393. struct XML xml={ lpXML,lpXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
  1394. pResults->nLine = 1;
  1395. pResults->nColumn = 1;
  1396. while (xml.nIndex<nUpto)
  1397. {
  1398. ch = getNextChar(&xml);
  1399. if (ch != _T('\n')) pResults->nColumn++;
  1400. else
  1401. {
  1402. pResults->nLine++;
  1403. pResults->nColumn=1;
  1404. }
  1405. }
  1406. }
  1407. // Parse XML and return the root element.
  1408. XMLNode XMLNode::parseString(XMLCSTR lpszXML, XMLCSTR tag, XMLResults *pResults)
  1409. {
  1410. if (!lpszXML)
  1411. {
  1412. if (pResults)
  1413. {
  1414. pResults->error=eXMLErrorNoElements;
  1415. pResults->nLine=0;
  1416. pResults->nColumn=0;
  1417. }
  1418. return emptyXMLNode;
  1419. }
  1420. XMLNode xnode(NULL,NULL,FALSE);
  1421. struct XML xml={ lpszXML, lpszXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
  1422. // Create header element
  1423. xnode.ParseXMLElement(&xml);
  1424. enum XMLError error = xml.error;
  1425. if ((xnode.nChildNode()==1)&&(xnode.nElement()==1)) xnode=xnode.getChildNode(); // skip the empty node
  1426. // If no error occurred
  1427. if ((error==eXMLErrorNone)||(error==eXMLErrorMissingEndTag))
  1428. {
  1429. XMLCSTR name=xnode.getName();
  1430. if (tag&&_tcslen(tag)&&((!name)||(_tcsicmp(xnode.getName(),tag))))
  1431. {
  1432. XMLNode nodeTmp;
  1433. int i=0;
  1434. while (i<xnode.nChildNode())
  1435. {
  1436. nodeTmp=xnode.getChildNode(i);
  1437. if (_tcsicmp(nodeTmp.getName(),tag)==0) break;
  1438. if (nodeTmp.isDeclaration()) { xnode=nodeTmp; i=0; } else i++;
  1439. }
  1440. if (i>=xnode.nChildNode())
  1441. {
  1442. if (pResults)
  1443. {
  1444. pResults->error=eXMLErrorFirstTagNotFound;
  1445. pResults->nLine=0;
  1446. pResults->nColumn=0;
  1447. }
  1448. return emptyXMLNode;
  1449. }
  1450. xnode=nodeTmp;
  1451. }
  1452. } else
  1453. {
  1454. // Cleanup: this will destroy all the nodes
  1455. xnode = emptyXMLNode;
  1456. }
  1457. // If we have been given somewhere to place results
  1458. if (pResults)
  1459. {
  1460. pResults->error = error;
  1461. // If we have an error
  1462. if (error!=eXMLErrorNone)
  1463. {
  1464. if (error==eXMLErrorMissingEndTag) xml.nIndex=xml.nIndexMissigEndTag;
  1465. // Find which line and column it starts on.
  1466. CountLinesAndColumns(xml.lpXML, xml.nIndex, pResults);
  1467. }
  1468. }
  1469. return xnode;
  1470. }
  1471. XMLNode XMLNode::parseFile(XMLCSTR filename, XMLCSTR tag, XMLResults *pResults)
  1472. {
  1473. if (pResults) { pResults->nLine=0; pResults->nColumn=0; }
  1474. FILE *f=_tfopen(filename,_T("rb"));
  1475. if (f==NULL) { if (pResults) pResults->error=eXMLErrorFileNotFound; return emptyXMLNode; }
  1476. fseek(f,0,SEEK_END);
  1477. int l=ftell(f),headerSz=0;
  1478. if (!l) { if (pResults) pResults->error=eXMLErrorEmpty; return emptyXMLNode; }
  1479. fseek(f,0,SEEK_SET);
  1480. unsigned char *buf=(unsigned char*)malloc(l+1);
  1481. int tmp=fread(buf,l,1,f);
  1482. (void)tmp;
  1483. fclose(f);
  1484. buf[l]=0;
  1485. #ifdef _XMLUNICODE
  1486. if (guessUnicodeChars)
  1487. {
  1488. if (!myIsTextUnicode(buf,l))
  1489. {
  1490. if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) headerSz=3;
  1491. XMLSTR b2=myMultiByteToWideChar((const char*)(buf+headerSz),l-headerSz);
  1492. free(buf); buf=(unsigned char*)b2; headerSz=0;
  1493. } else
  1494. {
  1495. if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
  1496. if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
  1497. }
  1498. }
  1499. #else
  1500. if (guessUnicodeChars)
  1501. {
  1502. if (myIsTextUnicode(buf,l))
  1503. {
  1504. l/=sizeof(wchar_t);
  1505. if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
  1506. if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
  1507. char *b2=myWideCharToMultiByte((const wchar_t*)(buf+headerSz),l-headerSz);
  1508. free(buf); buf=(unsigned char*)b2; headerSz=0;
  1509. } else
  1510. {
  1511. if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) headerSz=3;
  1512. }
  1513. }
  1514. #endif
  1515. if (!buf) { if (pResults) pResults->error=eXMLErrorCharConversionError; return emptyXMLNode; }
  1516. XMLNode x=parseString((XMLSTR)(buf+headerSz),tag,pResults);
  1517. free(buf);
  1518. return x;
  1519. }
  1520. static inline void charmemset(XMLSTR dest,XMLCHAR c,int l) { while (l--) *(dest++)=c; }
  1521. // private:
  1522. // Creates an user friendly XML string from a given element with
  1523. // appropriate white space and carriage returns.
  1524. //
  1525. // This recurses through all subnodes then adds contents of the nodes to the
  1526. // string.
  1527. int XMLNode::CreateXMLStringR(XMLNodeData *pEntry, XMLSTR lpszMarker, int nFormat)
  1528. {
  1529. int nResult = 0;
  1530. int cb;
  1531. int cbElement;
  1532. int nChildFormat=-1;
  1533. int nElementI=pEntry->nChild+pEntry->nText+pEntry->nClear;
  1534. int i,j;
  1535. assert(pEntry);
  1536. #define LENSTR(lpsz) (lpsz ? _tcslen(lpsz) : 0)
  1537. // If the element has no name then assume this is the head node.
  1538. cbElement = (int)LENSTR(pEntry->lpszName);
  1539. if (cbElement)
  1540. {
  1541. // "<elementname "
  1542. cb = nFormat == -1 ? 0 : nFormat;
  1543. if (lpszMarker)
  1544. {
  1545. if (cb) charmemset(lpszMarker, INDENTCHAR, sizeof(XMLCHAR)*cb);
  1546. nResult = cb;
  1547. lpszMarker[nResult++]=_T('<');
  1548. if (pEntry->isDeclaration) lpszMarker[nResult++]=_T('?');
  1549. _tcscpy(&lpszMarker[nResult], pEntry->lpszName);
  1550. nResult+=cbElement;
  1551. lpszMarker[nResult++]=_T(' ');
  1552. } else
  1553. {
  1554. nResult+=cbElement+2+cb;
  1555. if (pEntry->isDeclaration) nResult++;
  1556. }
  1557. // Enumerate attributes and add them to the string
  1558. XMLAttribute *pAttr=pEntry->pAttribute;
  1559. for (i=0; i<pEntry->nAttribute; i++)
  1560. {
  1561. // "Attrib
  1562. cb = (int)LENSTR(pAttr->lpszName);
  1563. if (cb)
  1564. {
  1565. if (lpszMarker) _tcscpy(&lpszMarker[nResult], pAttr->lpszName);
  1566. nResult += cb;
  1567. // "Attrib=Value "
  1568. if (pAttr->lpszValue)
  1569. {
  1570. cb=(int)lengthXMLString(pAttr->lpszValue);
  1571. if (lpszMarker)
  1572. {
  1573. lpszMarker[nResult]=_T('=');
  1574. lpszMarker[nResult+1]=_T('"');
  1575. if (cb) toXMLString(&lpszMarker[nResult+2],pAttr->lpszValue);
  1576. lpszMarker[nResult+cb+2]=_T('"');
  1577. }
  1578. nResult+=cb+3;
  1579. }
  1580. if (lpszMarker) lpszMarker[nResult] = _T(' ');
  1581. nResult++;
  1582. }
  1583. pAttr++;
  1584. }
  1585. if (pEntry->isDeclaration)
  1586. {
  1587. if (lpszMarker)
  1588. {
  1589. lpszMarker[nResult-1]=_T('?');
  1590. lpszMarker[nResult]=_T('>');
  1591. }
  1592. nResult++;
  1593. if (nFormat!=-1)
  1594. {
  1595. if (lpszMarker) lpszMarker[nResult]=_T('\n');
  1596. nResult++;
  1597. }
  1598. } else
  1599. // If there are child nodes we need to terminate the start tag
  1600. if (nElementI)
  1601. {
  1602. if (lpszMarker) lpszMarker[nResult-1]=_T('>');
  1603. if (nFormat!=-1)
  1604. {
  1605. if (lpszMarker) lpszMarker[nResult]=_T('\n');
  1606. nResult++;
  1607. }
  1608. } else nResult--;
  1609. }
  1610. // Calculate the child format for when we recurse. This is used to
  1611. // determine the number of spaces used for prefixes.
  1612. if (nFormat!=-1)
  1613. {
  1614. if (cbElement&&(!pEntry->isDeclaration)) nChildFormat=nFormat+1;
  1615. else nChildFormat=nFormat;
  1616. }
  1617. // Enumerate through remaining children
  1618. for (i=0; i<nElementI; i++)
  1619. {
  1620. j=pEntry->pOrder[i];
  1621. switch((XMLElementType)(j&3))
  1622. {
  1623. // Text nodes
  1624. case eNodeText:
  1625. {
  1626. // "Text"
  1627. XMLCSTR pChild=pEntry->pText[j>>2];
  1628. cb = (int)lengthXMLString(pChild);
  1629. if (cb)
  1630. {
  1631. if (nFormat!=-1)
  1632. {
  1633. if (lpszMarker)
  1634. {
  1635. charmemset(&lpszMarker[nResult],INDENTCHAR,sizeof(XMLCHAR)*(nFormat + 1));
  1636. toXMLString(&lpszMarker[nResult+nFormat+1],pChild);
  1637. lpszMarker[nResult+nFormat+1+cb]=_T('\n');
  1638. }
  1639. nResult+=cb+nFormat+2;
  1640. } else
  1641. {
  1642. if (lpszMarker) toXMLString(&lpszMarker[nResult], pChild);
  1643. nResult += cb;
  1644. }
  1645. }
  1646. break;
  1647. }
  1648. // Clear type nodes
  1649. case eNodeClear:
  1650. {
  1651. XMLClear *pChild=pEntry->pClear+(j>>2);
  1652. // "OpenTag"
  1653. cb = (int)LENSTR(pChild->lpszOpenTag);
  1654. if (cb)
  1655. {
  1656. if (nFormat!=-1)
  1657. {
  1658. if (lpszMarker)
  1659. {
  1660. charmemset(&lpszMarker[nResult], INDENTCHAR, sizeof(XMLCHAR)*(nFormat + 1));
  1661. _tcscpy(&lpszMarker[nResult+nFormat+1], pChild->lpszOpenTag);
  1662. }
  1663. nResult+=cb+nFormat+1;
  1664. }
  1665. else
  1666. {
  1667. if (lpszMarker)_tcscpy(&lpszMarker[nResult], pChild->lpszOpenTag);
  1668. nResult += cb;
  1669. }
  1670. }
  1671. // "OpenTag Value"
  1672. cb = (int)LENSTR(pChild->lpszValue);
  1673. if (cb)
  1674. {
  1675. if (lpszMarker) _tcscpy(&lpszMarker[nResult], pChild->lpszValue);
  1676. nResult += cb;
  1677. }
  1678. // "OpenTag Value CloseTag"
  1679. cb = (int)LENSTR(pChild->lpszCloseTag);
  1680. if (cb)
  1681. {
  1682. if (lpszMarker) _tcscpy(&lpszMarker[nResult], pChild->lpszCloseTag);
  1683. nResult += cb;
  1684. }
  1685. if (nFormat!=-1)
  1686. {
  1687. if (lpszMarker) lpszMarker[nResult] = _T('\n');
  1688. nResult++;
  1689. }
  1690. break;
  1691. }
  1692. // Element nodes
  1693. case eNodeChild:
  1694. {
  1695. // Recursively add child nodes
  1696. nResult += CreateXMLStringR(pEntry->pChild[j>>2].d, lpszMarker ? lpszMarker + nResult : 0, nChildFormat);
  1697. break;
  1698. }
  1699. default: break;
  1700. }
  1701. }
  1702. if ((cbElement)&&(!pEntry->isDeclaration))
  1703. {
  1704. // If we have child entries we need to use long XML notation for
  1705. // closing the element - "<elementname>blah blah blah</elementname>"
  1706. if (nElementI)
  1707. {
  1708. // "</elementname>\0"
  1709. if (lpszMarker)
  1710. {
  1711. if (nFormat != -1)
  1712. {
  1713. if (nFormat)
  1714. {
  1715. charmemset(&lpszMarker[nResult], INDENTCHAR,sizeof(XMLCHAR)*nFormat);
  1716. nResult+=nFormat;
  1717. }
  1718. }
  1719. _tcscpy(&lpszMarker[nResult], _T("</"));
  1720. nResult += 2;
  1721. _tcscpy(&lpszMarker[nResult], pEntry->lpszName);
  1722. nResult += cbElement;
  1723. if (nFormat == -1)
  1724. {
  1725. _tcscpy(&lpszMarker[nResult], _T(">"));
  1726. nResult++;
  1727. } else
  1728. {
  1729. _tcscpy(&lpszMarker[nResult], _T(">\n"));
  1730. nResult+=2;
  1731. }
  1732. } else
  1733. {
  1734. if (nFormat != -1) nResult+=cbElement+4+nFormat;
  1735. else nResult+=cbElement+3;
  1736. }
  1737. } else
  1738. {
  1739. // If there are no children we can use shorthand XML notation -
  1740. // "<elementname/>"
  1741. // "/>\0"
  1742. if (lpszMarker)
  1743. {
  1744. if (nFormat == -1)
  1745. {
  1746. _tcscpy(&lpszMarker[nResult], _T("/>"));
  1747. nResult += 2;
  1748. }
  1749. else
  1750. {
  1751. _tcscpy(&lpszMarker[nResult], _T("/>\n"));
  1752. nResult += 3;
  1753. }
  1754. }
  1755. else
  1756. {
  1757. nResult += nFormat == -1 ? 2 : 3;
  1758. }
  1759. }
  1760. }
  1761. return nResult;
  1762. }
  1763. #undef LENSTR
  1764. // Create an XML string
  1765. // @param int nFormat - 0 if no formatting is required
  1766. // otherwise nonzero for formatted text
  1767. // with carriage returns and indentation.
  1768. // @param int *pnSize - [out] pointer to the size of the
  1769. // returned string not including the
  1770. // NULL terminator.
  1771. // @return XMLSTR - Allocated XML string, you must free
  1772. // this with free().
  1773. XMLSTR XMLNode::createXMLString(int nFormat, int *pnSize) const
  1774. {
  1775. if (!d) { if (pnSize) *pnSize=0; return NULL; }
  1776. XMLSTR lpszResult = NULL;
  1777. int cbStr;
  1778. // Recursively Calculate the size of the XML string
  1779. if (!dropWhiteSpace) nFormat=0;
  1780. nFormat = nFormat ? 0 : -1;
  1781. cbStr = CreateXMLStringR(d, 0, nFormat);
  1782. assert(cbStr);
  1783. // Alllocate memory for the XML string + the NULL terminator and
  1784. // create the recursively XML string.
  1785. lpszResult=(XMLSTR)malloc((cbStr+1)*sizeof(XMLCHAR));
  1786. CreateXMLStringR(d, lpszResult, nFormat);
  1787. if (pnSize) *pnSize = cbStr;
  1788. return lpszResult;
  1789. }
  1790. XMLNode::~XMLNode() { deleteNodeContent(); }
  1791. int XMLNode::detachFromParent(XMLNodeData *d)
  1792. {
  1793. XMLNode *pa=d->pParent->pChild;
  1794. int i=0;
  1795. while (((void*)(pa[i].d))!=((void*)d)) i++;
  1796. d->pParent->nChild--;
  1797. if (d->pParent->nChild) memmove(pa+i,pa+i+1,(d->pParent->nChild-i)*sizeof(XMLNode));
  1798. else { free(pa); d->pParent->pChild=NULL; }
  1799. return removeOrderElement(d->pParent,eNodeChild,i);
  1800. }
  1801. void XMLNode::deleteNodeContent(char force)
  1802. {
  1803. if (!d) return;
  1804. (d->ref_count) --;
  1805. if ((d->ref_count==0)||force)
  1806. {
  1807. int i;
  1808. if (d->pParent) detachFromParent(d);
  1809. for(i=0; i<d->nChild; i++) { d->pChild[i].d->pParent=NULL; d->pChild[i].deleteNodeContent(force); }
  1810. free(d->pChild);
  1811. for(i=0; i<d->nText; i++) free((void*)d->pText[i]);
  1812. free(d->pText);
  1813. for(i=0; i<d->nClear; i++) free((void*)d->pClear[i].lpszValue);
  1814. free(d->pClear);
  1815. for(i=0; i<d->nAttribute; i++)
  1816. {
  1817. free((void*)d->pAttribute[i].lpszName);
  1818. if (d->pAttribute[i].lpszValue) free((void*)d->pAttribute[i].lpszValue);
  1819. }
  1820. free(d->pAttribute);
  1821. free(d->pOrder);
  1822. free((void*)d->lpszName);
  1823. free(d);
  1824. d=NULL;
  1825. }
  1826. }
  1827. XMLNode XMLNode::addChild(XMLNode childNode, int pos)
  1828. {
  1829. XMLNodeData *dc=childNode.d;
  1830. if ((!dc)||(!d)) return childNode;
  1831. if (dc->pParent) { if ((detachFromParent(dc)<=pos)&&(dc->pParent==d)) pos--; } else dc->ref_count++;
  1832. dc->pParent=d;
  1833. // int nc=d->nChild;
  1834. // d->pChild=(XMLNode*)myRealloc(d->pChild,(nc+1),memoryIncrease,sizeof(XMLNode));
  1835. d->pChild=(XMLNode*)addToOrder(0,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
  1836. d->pChild[pos].d=dc;
  1837. d->nChild++;
  1838. return childNode;
  1839. }
  1840. void XMLNode::deleteAttribute(int i)
  1841. {
  1842. if ((!d)||(i<0)||(i>=d->nAttribute)) return;
  1843. d->nAttribute--;
  1844. XMLAttribute *p=d->pAttribute+i;
  1845. free((void*)p->lpszName);
  1846. if (p->lpszValue) free((void*)p->lpszValue);
  1847. if (d->nAttribute) memmove(p,p+1,(d->nAttribute-i)*sizeof(XMLAttribute)); else { free(p); d->pAttribute=NULL; }
  1848. }
  1849. void XMLNode::deleteAttribute(XMLAttribute *a){ if (a) deleteAttribute(a->lpszName); }
  1850. void XMLNode::deleteAttribute(XMLCSTR lpszName)
  1851. {
  1852. int j=0;
  1853. getAttribute(lpszName,&j);
  1854. if (j) deleteAttribute(j-1);
  1855. }
  1856. XMLAttribute *XMLNode::updateAttribute_WOSD(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,int i)
  1857. {
  1858. if (!d) return NULL;
  1859. if (i>=d->nAttribute)
  1860. {
  1861. if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
  1862. return NULL;
  1863. }
  1864. XMLAttribute *p=d->pAttribute+i;
  1865. if (p->lpszValue&&p->lpszValue!=lpszNewValue) free((void*)p->lpszValue);
  1866. p->lpszValue=lpszNewValue;
  1867. if (lpszNewName&&p->lpszName!=lpszNewName) { free((void*)p->lpszName); p->lpszName=lpszNewName; };
  1868. return p;
  1869. }
  1870. XMLAttribute *XMLNode::updateAttribute_WOSD(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
  1871. {
  1872. if (oldAttribute) return updateAttribute_WOSD(newAttribute->lpszValue,newAttribute->lpszName,oldAttribute->lpszName);
  1873. return addAttribute_WOSD(newAttribute->lpszName,newAttribute->lpszValue);
  1874. }
  1875. XMLAttribute *XMLNode::updateAttribute_WOSD(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,XMLCSTR lpszOldName)
  1876. {
  1877. int j=0;
  1878. getAttribute(lpszOldName,&j);
  1879. if (j) return updateAttribute_WOSD(lpszNewValue,lpszNewName,j-1);
  1880. else
  1881. {
  1882. if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
  1883. else return addAttribute_WOSD(stringDup(lpszOldName),lpszNewValue);
  1884. }
  1885. }
  1886. int XMLNode::indexText(XMLCSTR lpszValue) const
  1887. {
  1888. if (!d) return -1;
  1889. int i,l=d->nText;
  1890. if (!lpszValue) { if (l) return 0; return -1; }
  1891. XMLCSTR *p=d->pText;
  1892. for (i=0; i<l; i++) if (lpszValue==p[i]) return i;
  1893. return -1;
  1894. }
  1895. void XMLNode::deleteText(int i)
  1896. {
  1897. if ((!d)||(i<0)||(i>=d->nText)) return;
  1898. d->nText--;
  1899. XMLCSTR *p=d->pText+i;
  1900. free((void*)*p);
  1901. if (d->nText) memmove(p,p+1,(d->nText-i)*sizeof(XMLCSTR)); else { free(p); d->pText=NULL; }
  1902. removeOrderElement(d,eNodeText,i);
  1903. }
  1904. void XMLNode::deleteText(XMLCSTR lpszValue) { deleteText(indexText(lpszValue)); }
  1905. XMLCSTR XMLNode::updateText_WOSD(XMLCSTR lpszNewValue, int i)
  1906. {
  1907. if (!d) return NULL;
  1908. if (i>=d->nText) return addText_WOSD(lpszNewValue);
  1909. XMLCSTR *p=d->pText+i;
  1910. if (*p!=lpszNewValue) { free((void*)*p); *p=lpszNewValue; }
  1911. return lpszNewValue;
  1912. }
  1913. XMLCSTR XMLNode::updateText_WOSD(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
  1914. {
  1915. if (!d) return NULL;
  1916. int i=indexText(lpszOldValue);
  1917. if (i>=0) return updateText_WOSD(lpszNewValue,i);
  1918. return addText_WOSD(lpszNewValue);
  1919. }
  1920. void XMLNode::deleteClear(int i)
  1921. {
  1922. if ((!d)||(i<0)||(i>=d->nClear)) return;
  1923. d->nClear--;
  1924. XMLClear *p=d->pClear+i;
  1925. free((void*)p->lpszValue);
  1926. if (d->nClear) memmove(p,p+1,(d->nText-i)*sizeof(XMLClear)); else { free(p); d->pClear=NULL; }
  1927. removeOrderElement(d,eNodeClear,i);
  1928. }
  1929. int XMLNode::indexClear(XMLCSTR lpszValue) const
  1930. {
  1931. if (!d) return -1;
  1932. int i,l=d->nClear;
  1933. if (!lpszValue) { if (l) return 0; return -1; }
  1934. XMLClear *p=d->pClear;
  1935. for (i=0; i<l; i++) if (lpszValue==p[i].lpszValue) return i;
  1936. return -1;
  1937. }
  1938. void XMLNode::deleteClear(XMLCSTR lpszValue) { deleteClear(indexClear(lpszValue)); }
  1939. void XMLNode::deleteClear(XMLClear *a) { if (a) deleteClear(a->lpszValue); }
  1940. XMLClear *XMLNode::updateClear_WOSD(XMLCSTR lpszNewContent, int i)
  1941. {
  1942. if (!d) return NULL;
  1943. if (i>=d->nClear)
  1944. {
  1945. return addClear_WOSD(XMLClearTags[0].lpszOpen,lpszNewContent,XMLClearTags[0].lpszClose);
  1946. }
  1947. XMLClear *p=d->pClear+i;
  1948. if (lpszNewContent!=p->lpszValue) { free((void*)p->lpszValue); p->lpszValue=lpszNewContent; }
  1949. return p;
  1950. }
  1951. XMLClear *XMLNode::updateClear_WOSD(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
  1952. {
  1953. if (!d) return NULL;
  1954. int i=indexClear(lpszOldValue);
  1955. if (i>=0) return updateClear_WOSD(lpszNewValue,i);
  1956. return addClear_WOSD(lpszNewValue,XMLClearTags[0].lpszOpen,XMLClearTags[0].lpszClose);
  1957. }
  1958. XMLClear *XMLNode::updateClear_WOSD(XMLClear *newP,XMLClear *oldP)
  1959. {
  1960. if (oldP) return updateClear_WOSD(newP->lpszValue,oldP->lpszValue);
  1961. return NULL;
  1962. }
  1963. XMLNode& XMLNode::operator=( const XMLNode& A )
  1964. {
  1965. // shallow copy
  1966. if (this != &A)
  1967. {
  1968. deleteNodeContent();
  1969. d=A.d;
  1970. if (d) (d->ref_count) ++ ;
  1971. }
  1972. return *this;
  1973. }
  1974. XMLNode::XMLNode(const XMLNode &A)
  1975. {
  1976. // shallow copy
  1977. d=A.d;
  1978. if (d) (d->ref_count)++ ;
  1979. }
  1980. int XMLNode::nChildNode(XMLCSTR name) const
  1981. {
  1982. if (!d) return 0;
  1983. int i,j=0,n=d->nChild;
  1984. XMLNode *pc=d->pChild;
  1985. for (i=0; i<n; i++)
  1986. {
  1987. if (_tcsicmp(pc->d->lpszName, name)==0) j++;
  1988. pc++;
  1989. }
  1990. return j;
  1991. }
  1992. XMLNode XMLNode::getChildNode(XMLCSTR name, int *j) const
  1993. {
  1994. if (!d) return emptyXMLNode;
  1995. int i=0,n=d->nChild;
  1996. if (j) i=*j;
  1997. XMLNode *pc=d->pChild+i;
  1998. for (; i<n; i++)
  1999. {
  2000. if (_tcsicmp(pc->d->lpszName, name)==0)
  2001. {
  2002. if (j) *j=i+1;
  2003. return *pc;
  2004. }
  2005. pc++;
  2006. }
  2007. return emptyXMLNode;
  2008. }
  2009. XMLNode XMLNode::getChildNode(XMLCSTR name, int j) const
  2010. {
  2011. if (!d) return emptyXMLNode;
  2012. int i=0;
  2013. while (j-->0) getChildNode(name,&i);
  2014. return getChildNode(name,&i);
  2015. }
  2016. int XMLNode::positionOfText (int i) const { if (i>=d->nText ) i=d->nText-1; return findPosition(d,i,eNodeText ); }
  2017. int XMLNode::positionOfClear (int i) const { if (i>=d->nClear) i=d->nClear-1; return findPosition(d,i,eNodeClear); }
  2018. int XMLNode::positionOfChildNode(int i) const { if (i>=d->nChild) i=d->nChild-1; return findPosition(d,i,eNodeChild); }
  2019. int XMLNode::positionOfText (XMLCSTR lpszValue) const { return positionOfText (indexText (lpszValue)); }
  2020. int XMLNode::positionOfClear(XMLCSTR lpszValue) const { return positionOfClear(indexClear(lpszValue)); }
  2021. int XMLNode::positionOfClear(XMLClear *a) const { if (a) return positionOfClear(a->lpszValue); return positionOfClear(); }
  2022. int XMLNode::positionOfChildNode(XMLNode x) const
  2023. {
  2024. if ((!d)||(!x.d)) return -1;
  2025. XMLNodeData *dd=x.d;
  2026. XMLNode *pc=d->pChild;
  2027. int i=d->nChild;
  2028. while (i--) if (pc[i].d==dd) return findPosition(d,i,eNodeChild);
  2029. return -1;
  2030. }
  2031. int XMLNode::positionOfChildNode(XMLCSTR name, int count) const
  2032. {
  2033. if (!name) return positionOfChildNode(count);
  2034. int j=0;
  2035. do { getChildNode(name,&j); if (j<0) return -1; } while (count--);
  2036. return findPosition(d,j-1,eNodeChild);
  2037. }
  2038. XMLNode XMLNode::getChildNodeWithAttribute(XMLCSTR name,XMLCSTR attributeName,XMLCSTR attributeValue, int *k) const
  2039. {
  2040. int i=0,j;
  2041. if (k) i=*k;
  2042. XMLNode x;
  2043. XMLCSTR t;
  2044. do
  2045. {
  2046. x=getChildNode(name,&i);
  2047. if (!x.isEmpty())
  2048. {
  2049. if (attributeValue)
  2050. {
  2051. j=0;
  2052. do
  2053. {
  2054. t=x.getAttribute(attributeName,&j);
  2055. if (t&&(_tcsicmp(attributeValue,t)==0)) { if (k) *k=i+1; return x; }
  2056. } while (t);
  2057. } else
  2058. {
  2059. if (x.isAttributeSet(attributeName)) { if (k) *k=i+1; return x; }
  2060. }
  2061. }
  2062. } while (!x.isEmpty());
  2063. return emptyXMLNode;
  2064. }
  2065. // Find an attribute on an node.
  2066. XMLCSTR XMLNode::getAttribute(XMLCSTR lpszAttrib, int *j) const
  2067. {
  2068. if (!d) return NULL;
  2069. int i=0,n=d->nAttribute;
  2070. if (j) i=*j;
  2071. XMLAttribute *pAttr=d->pAttribute+i;
  2072. for (; i<n; i++)
  2073. {
  2074. if (_tcsicmp(pAttr->lpszName, lpszAttrib)==0)
  2075. {
  2076. if (j) *j=i+1;
  2077. return pAttr->lpszValue;
  2078. }
  2079. pAttr++;
  2080. }
  2081. return NULL;
  2082. }
  2083. char XMLNode::isAttributeSet(XMLCSTR lpszAttrib) const
  2084. {
  2085. if (!d) return FALSE;
  2086. int i,n=d->nAttribute;
  2087. XMLAttribute *pAttr=d->pAttribute;
  2088. for (i=0; i<n; i++)
  2089. {
  2090. if (_tcsicmp(pAttr->lpszName, lpszAttrib)==0)
  2091. {
  2092. return TRUE;
  2093. }
  2094. pAttr++;
  2095. }
  2096. return FALSE;
  2097. }
  2098. XMLCSTR XMLNode::getAttribute(XMLCSTR name, int j) const
  2099. {
  2100. if (!d) return NULL;
  2101. int i=0;
  2102. while (j-->0) getAttribute(name,&i);
  2103. return getAttribute(name,&i);
  2104. }
  2105. XMLNodeContents XMLNode::enumContents(int i) const
  2106. {
  2107. XMLNodeContents c;
  2108. if (!d) { c.type=eNodeNULL; return c; }
  2109. if (i<d->nAttribute)
  2110. {
  2111. c.type=eNodeAttribute;
  2112. c.attrib=d->pAttribute[i];
  2113. return c;
  2114. }
  2115. i-=d->nAttribute;
  2116. c.type=(XMLElementType)(d->pOrder[i]&3);
  2117. i=(d->pOrder[i])>>2;
  2118. switch (c.type)
  2119. {
  2120. case eNodeChild: c.child = d->pChild[i]; break;
  2121. case eNodeText: c.text = d->pText[i]; break;
  2122. case eNodeClear: c.clear = d->pClear[i]; break;
  2123. default: break;
  2124. }
  2125. return c;
  2126. }
  2127. XMLCSTR XMLNode::getName() const { if (!d) return NULL; return d->lpszName; }
  2128. int XMLNode::nText() const { if (!d) return 0; return d->nText; }
  2129. int XMLNode::nChildNode() const { if (!d) return 0; return d->nChild; }
  2130. int XMLNode::nAttribute() const { if (!d) return 0; return d->nAttribute; }
  2131. int XMLNode::nClear() const { if (!d) return 0; return d->nClear; }
  2132. int XMLNode::nElement() const { if (!d) return 0; return d->nAttribute+d->nChild+d->nText+d->nClear; }
  2133. XMLClear XMLNode::getClear (int i) const { if ((!d)||(i>=d->nClear )) return emptyXMLClear; return d->pClear[i]; }
  2134. XMLAttribute XMLNode::getAttribute (int i) const { if ((!d)||(i>=d->nAttribute)) return emptyXMLAttribute; return d->pAttribute[i]; }
  2135. XMLCSTR XMLNode::getAttributeName (int i) const { if ((!d)||(i>=d->nAttribute)) return NULL; return d->pAttribute[i].lpszName; }
  2136. XMLCSTR XMLNode::getAttributeValue(int i) const { if ((!d)||(i>=d->nAttribute)) return NULL; return d->pAttribute[i].lpszValue; }
  2137. XMLCSTR XMLNode::getText (int i) const { if ((!d)||(i>=d->nText )) return NULL; return d->pText[i]; }
  2138. XMLNode XMLNode::getChildNode (int i) const { if ((!d)||(i>=d->nChild )) return emptyXMLNode; return d->pChild[i]; }
  2139. XMLNode XMLNode::getParentNode ( ) const { if ((!d)||(!d->pParent )) return emptyXMLNode; return XMLNode(d->pParent); }
  2140. char XMLNode::isDeclaration ( ) const { if (!d) return 0; return d->isDeclaration; }
  2141. char XMLNode::isEmpty ( ) const { return (d==NULL); }
  2142. XMLNode XMLNode::addChild(XMLCSTR lpszName, char isDeclaration, int pos)
  2143. { return addChild_priv(0,stringDup(lpszName),isDeclaration,pos); }
  2144. XMLNode XMLNode::addChild_WOSD(XMLCSTR lpszName, char isDeclaration, int pos)
  2145. { return addChild_priv(0,lpszName,isDeclaration,pos); }
  2146. XMLAttribute *XMLNode::addAttribute(XMLCSTR lpszName, XMLCSTR lpszValue)
  2147. { return addAttribute_priv(0,stringDup(lpszName),stringDup(lpszValue)); }
  2148. XMLAttribute *XMLNode::addAttribute_WOSD(XMLCSTR lpszName, XMLCSTR lpszValuev)
  2149. { return addAttribute_priv(0,lpszName,lpszValuev); }
  2150. XMLCSTR XMLNode::addText(XMLCSTR lpszValue, int pos)
  2151. { return addText_priv(0,stringDup(lpszValue),pos); }
  2152. XMLCSTR XMLNode::addText_WOSD(XMLCSTR lpszValue, int pos)
  2153. { return addText_priv(0,lpszValue,pos); }
  2154. XMLClear *XMLNode::addClear(XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
  2155. { return addClear_priv(0,stringDup(lpszValue),lpszOpen,lpszClose,pos); }
  2156. XMLClear *XMLNode::addClear_WOSD(XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
  2157. { return addClear_priv(0,lpszValue,lpszOpen,lpszClose,pos); }
  2158. XMLCSTR XMLNode::updateName(XMLCSTR lpszName)
  2159. { return updateName_WOSD(stringDup(lpszName)); }
  2160. XMLAttribute *XMLNode::updateAttribute(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
  2161. { return updateAttribute_WOSD(stringDup(newAttribute->lpszValue),stringDup(newAttribute->lpszName),oldAttribute->lpszName); }
  2162. XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,int i)
  2163. { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),i); }
  2164. XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,XMLCSTR lpszOldName)
  2165. { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),lpszOldName); }
  2166. XMLCSTR XMLNode::updateText(XMLCSTR lpszNewValue, int i)
  2167. { return updateText_WOSD(stringDup(lpszNewValue),i); }
  2168. XMLCSTR XMLNode::updateText(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
  2169. { return updateText_WOSD(stringDup(lpszNewValue),lpszOldValue); }
  2170. XMLClear *XMLNode::updateClear(XMLCSTR lpszNewContent, int i)
  2171. { return updateClear_WOSD(stringDup(lpszNewContent),i); }
  2172. XMLClear *XMLNode::updateClear(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
  2173. { return updateClear_WOSD(stringDup(lpszNewValue),lpszOldValue); }
  2174. XMLClear *XMLNode::updateClear(XMLClear *newP,XMLClear *oldP)
  2175. { return updateClear_WOSD(stringDup(newP->lpszValue),oldP->lpszValue); }
  2176. void XMLNode::setGlobalOptions(char _guessUnicodeChars, char _strictUTF8Parsing, char _dropWhiteSpace)
  2177. {
  2178. guessUnicodeChars=_guessUnicodeChars; dropWhiteSpace=_dropWhiteSpace; strictUTF8Parsing=_strictUTF8Parsing;
  2179. #ifndef _XMLUNICODE
  2180. if (_strictUTF8Parsing) XML_ByteTable=XML_utf8ByteTable; else XML_ByteTable=XML_asciiByteTable;
  2181. #endif
  2182. }
  2183. char XMLNode::guessUTF8ParsingParameterValue(void *buf,int l, char useXMLEncodingAttribute)
  2184. {
  2185. #ifdef _XMLUNICODE
  2186. return 0;
  2187. #else
  2188. if (l<25) return 0;
  2189. if (myIsTextUnicode(buf,l)) return 0;
  2190. unsigned char *b=(unsigned char*)buf;
  2191. if ((b[0]==0xef)&&(b[1]==0xbb)&&(b[2]==0xbf)) return 1;
  2192. // Match utf-8 model ?
  2193. int i=0;
  2194. while (i<l)
  2195. switch (XML_utf8ByteTable[b[i]])
  2196. {
  2197. case 4: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) return 0; // 10bbbbbb ?
  2198. case 3: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) return 0; // 10bbbbbb ?
  2199. case 2: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) return 0; // 10bbbbbb ?
  2200. case 1: i++; break;
  2201. case 0: i=l;
  2202. }
  2203. if (!useXMLEncodingAttribute) return 1;
  2204. // if encoding is specified and different from utf-8 than it's non-utf8
  2205. // otherwise it's utf-8
  2206. char bb[201];
  2207. l=mmin(l,200);
  2208. memcpy(bb,buf,l); // copy buf into bb to be able to do "bb[l]=0"
  2209. bb[l]=0;
  2210. b=(unsigned char*)strstr(bb,"encoding");
  2211. if (!b) return 1;
  2212. b+=8; while XML_isSPACECHAR(*b) b++; if (*b!='=') return 1;
  2213. b++; while XML_isSPACECHAR(*b) b++; if ((*b!='\'')&&(*b!='"')) return 1;
  2214. b++; while XML_isSPACECHAR(*b) b++; if ((_strnicmp((char*)b,"utf-8",5)==0)||
  2215. (_strnicmp((char*)b,"utf8",4)==0)) return 1;
  2216. return 0;
  2217. #endif
  2218. }
  2219. #undef XML_isSPACECHAR
  2220. //////////////////////////////////////////////////////////
  2221. // Here starts the base64 conversion functions. //
  2222. //////////////////////////////////////////////////////////
  2223. static const char base64Fillchar = _T('='); // used to mark partial words at the end
  2224. // this lookup table defines the base64 encoding
  2225. XMLCSTR base64EncodeTable=_T("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  2226. // Decode Table gives the index of any valid base64 character in the Base64 table]
  2227. // 96: '=' - 97: space char - 98: illegal char - 99: end of string
  2228. const unsigned char base64DecodeTable[] = {
  2229. 99,98,98,98,98,98,98,98,98,97, 97,98,98,97,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //00 -29
  2230. 98,98,97,98,98,98,98,98,98,98, 98,98,98,62,98,98,98,63,52,53, 54,55,56,57,58,59,60,61,98,98, //30 -59
  2231. 98,96,98,98,98, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, 15,16,17,18,19,20,21,22,23,24, //60 -89
  2232. 25,98,98,98,98,98,98,26,27,28, 29,30,31,32,33,34,35,36,37,38, 39,40,41,42,43,44,45,46,47,48, //90 -119
  2233. 49,50,51,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //120 -149
  2234. 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //150 -179
  2235. 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //180 -209
  2236. 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98,98,98,98,98, //210 -239
  2237. 98,98,98,98,98,98,98,98,98,98, 98,98,98,98,98,98 //240 -255
  2238. };
  2239. int XMLParserBase64Tool::encodeLength(int inlen, char formatted)
  2240. {
  2241. unsigned int i=((inlen-1)/3*4+4+1);
  2242. if (formatted) i+=inlen/54;
  2243. return i;
  2244. }
  2245. void XMLParserBase64Tool::encode(const std::string & inString, std::string & outString, char formatted)
  2246. {
  2247. unsigned char *inbuf = (unsigned char*)inString.data();
  2248. unsigned int inlen = inString.length();
  2249. encode(inbuf,inlen,outString,formatted);
  2250. }
  2251. void XMLParserBase64Tool::encode(unsigned char *inbuf, unsigned int inlen, std::string & outString, char formatted) {
  2252. int i=encodeLength(inlen,formatted),k=17,eLen=inlen/3,j;
  2253. outString.resize(i,0);
  2254. XMLSTR curr=(XMLSTR)outString.data();
  2255. // alloc(i*sizeof(XMLCHAR));
  2256. // XMLSTR curr=(XMLSTR)buf;
  2257. for(i=0;i<eLen;i++)
  2258. {
  2259. // Copy next three bytes into lower 24 bits of int, paying attention to sign.
  2260. j=(inbuf[0]<<16)|(inbuf[1]<<8)|inbuf[2]; inbuf+=3;
  2261. // Encode the int into four chars
  2262. *(curr++)=base64EncodeTable[ j>>18 ];
  2263. *(curr++)=base64EncodeTable[(j>>12)&0x3f];
  2264. *(curr++)=base64EncodeTable[(j>> 6)&0x3f];
  2265. *(curr++)=base64EncodeTable[(j )&0x3f];
  2266. if (formatted) { if (!k) { *(curr++)=_T('\n'); k=18; } k--; }
  2267. }
  2268. eLen=inlen-eLen*3; // 0 - 2.
  2269. if (eLen==1)
  2270. {
  2271. *(curr++)=base64EncodeTable[ inbuf[0]>>2 ];
  2272. *(curr++)=base64EncodeTable[(inbuf[0]<<4)&0x3F];
  2273. *(curr++)=base64Fillchar;
  2274. *(curr++)=base64Fillchar;
  2275. } else if (eLen==2)
  2276. {
  2277. j=(inbuf[0]<<8)|inbuf[1];
  2278. *(curr++)=base64EncodeTable[ j>>10 ];
  2279. *(curr++)=base64EncodeTable[(j>> 4)&0x3f];
  2280. *(curr++)=base64EncodeTable[(j<< 2)&0x3f];
  2281. *(curr++)=base64Fillchar;
  2282. }
  2283. *(curr++)=0;
  2284. }
  2285. unsigned int XMLParserBase64Tool::decodeSize(XMLCSTR data,XMLError *xe)
  2286. {
  2287. if (xe) *xe=eXMLErrorNone;
  2288. int size=0;
  2289. unsigned char c;
  2290. //skip any extra characters (e.g. newlines or spaces)
  2291. while (*data)
  2292. {
  2293. #ifdef _XMLUNICODE
  2294. if (*data>255) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
  2295. #endif
  2296. c=base64DecodeTable[(unsigned char)(*data)];
  2297. if (c<97) size++;
  2298. else if (c==98) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
  2299. data++;
  2300. }
  2301. if (xe&&(size%4!=0)) *xe=eXMLErrorBase64DataSizeIsNotMultipleOf4;
  2302. if (size==0) return 0;
  2303. do { data--; size--; } while(*data==base64Fillchar); size++;
  2304. return (unsigned int)((size*3)/4);
  2305. }
  2306. bool XMLParserBase64Tool::decode(const std::string & inString, unsigned char *buf, int len, XMLError *xe)
  2307. {
  2308. XMLCSTR data=inString.c_str();
  2309. if (xe) *xe=eXMLErrorNone;
  2310. int i=0,p=0;
  2311. unsigned char d,c;
  2312. for(;;)
  2313. {
  2314. #ifdef _XMLUNICODE
  2315. #define BASE64DECODE_READ_NEXT_CHAR(c) \
  2316. do { \
  2317. if (data[i]>255){ c=98; break; } \
  2318. c=base64DecodeTable[(unsigned char)data[i++]]; \
  2319. }while (c==97); \
  2320. if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return false; }
  2321. #else
  2322. #define BASE64DECODE_READ_NEXT_CHAR(c) \
  2323. do { c=base64DecodeTable[(unsigned char)data[i++]]; }while (c==97); \
  2324. if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return false; }
  2325. #endif
  2326. BASE64DECODE_READ_NEXT_CHAR(c)
  2327. if (c==99) { return true; }
  2328. if (c==96)
  2329. {
  2330. if (p==(int)len) return true;
  2331. if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;
  2332. return true;
  2333. }
  2334. BASE64DECODE_READ_NEXT_CHAR(d)
  2335. if ((d==99)||(d==96)) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return true; }
  2336. if (p==(int)len) { if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall; return false; }
  2337. buf[p++]=(c<<2)|((d>>4)&0x3);
  2338. BASE64DECODE_READ_NEXT_CHAR(c)
  2339. if (c==99) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return true; }
  2340. if (p==(int)len)
  2341. {
  2342. if (c==96) return true;
  2343. if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
  2344. return false;
  2345. }
  2346. if (c==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return true; }
  2347. buf[p++]=((d<<4)&0xf0)|((c>>2)&0xf);
  2348. BASE64DECODE_READ_NEXT_CHAR(d)
  2349. if (d==99 ) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return true; }
  2350. if (p==(int)len)
  2351. {
  2352. if (d==96) return true;
  2353. if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
  2354. return false;
  2355. }
  2356. if (d==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData; return true; }
  2357. buf[p++]=((c<<6)&0xc0)|d;
  2358. }
  2359. }
  2360. #undef BASE64DECODE_READ_NEXT_CHAR
  2361. bool XMLParserBase64Tool::decode(const std::string & inString, std::string & outString, XMLError *xe)
  2362. //unsigned char *XMLParserBase64Tool::decode(XMLCSTR data, int *outlen, XMLError *xe)
  2363. {
  2364. if (xe) *xe=eXMLErrorNone;
  2365. unsigned int len=decodeSize(inString.c_str(),xe);
  2366. if (!len) return false;
  2367. outString.resize(len+1,0);
  2368. return decode(inString,(unsigned char *)outString.data(),len,xe);
  2369. }
  2370. };