PageRenderTime 78ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/miranda/src/modules/xml/xmlParser.cpp

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