PageRenderTime 72ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/ThirdParty/xmlParser/xmlParser.cpp

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