xmlParser.cpp 108 KB

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