tinyxml2.cpp 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060
  1. /*
  2. Original code by Lee Thomason (www.grinninglizard.com)
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any
  5. damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any
  7. purpose, including commercial applications, and to alter it and
  8. redistribute it freely, subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must
  10. not claim that you wrote the original software. If you use this
  11. software in a product, an acknowledgment in the product documentation
  12. would be appreciated but is not required.
  13. 2. Altered source versions must be plainly marked as such, and
  14. must not be misrepresented as being the original software.
  15. 3. This notice may not be removed or altered from any source
  16. distribution.
  17. */
  18. #include "tinyxml2.h"
  19. #include <new> // yes, this one new style header, is in the Android SDK.
  20. #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) || defined(__CC_ARM)
  21. # include <stddef.h>
  22. # include <stdarg.h>
  23. #else
  24. # include <cstddef>
  25. # include <cstdarg>
  26. #endif
  27. // Handle fallthrough attribute for different compilers
  28. #ifndef __has_attribute
  29. # define __has_attribute(x) 0
  30. #endif
  31. #ifdef __cplusplus
  32. # ifndef __has_cpp_attribute
  33. # define __has_cpp_attribute(x) 0
  34. # endif
  35. #else
  36. # ifndef __has_c_attribute
  37. # define __has_c_attribute(x) 0
  38. # endif
  39. #endif
  40. #ifdef __cplusplus
  41. # if defined(_MSC_VER)
  42. # define TIXML_FALLTHROUGH (void(0))
  43. # elif (__cplusplus >= 201703L && __has_cpp_attribute(fallthrough))
  44. # define TIXML_FALLTHROUGH [[fallthrough]]
  45. # elif __has_cpp_attribute(clang::fallthrough)
  46. # define TIXML_FALLTHROUGH [[clang::fallthrough]]
  47. # elif __has_attribute(fallthrough)
  48. # define TIXML_FALLTHROUGH __attribute__((fallthrough))
  49. # else
  50. # define TIXML_FALLTHROUGH (void(0))
  51. # endif
  52. #else
  53. # if defined(_MSC_VER)
  54. # define TIXML_FALLTHROUGH (void(0))
  55. # elif __has_c_attribute(fallthrough)
  56. # define TIXML_FALLTHROUGH [[fallthrough]]
  57. # elif __has_attribute(fallthrough)
  58. # define TIXML_FALLTHROUGH __attribute__((fallthrough))
  59. # else
  60. # define TIXML_FALLTHROUGH (void(0))
  61. # endif
  62. #endif
  63. #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE)
  64. // Microsoft Visual Studio, version 2005 and higher. Not WinCE.
  65. /*int _snprintf_s(
  66. char *buffer,
  67. size_t sizeOfBuffer,
  68. size_t count,
  69. const char *format [,
  70. argument] ...
  71. );*/
  72. static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... )
  73. {
  74. va_list va;
  75. va_start( va, format );
  76. const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va );
  77. va_end( va );
  78. return result;
  79. }
  80. static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va )
  81. {
  82. const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va );
  83. return result;
  84. }
  85. #define TIXML_VSCPRINTF _vscprintf
  86. #define TIXML_SSCANF sscanf_s
  87. #elif defined _MSC_VER
  88. // Microsoft Visual Studio 2003 and earlier or WinCE
  89. #define TIXML_SNPRINTF _snprintf
  90. #define TIXML_VSNPRINTF _vsnprintf
  91. #define TIXML_SSCANF sscanf
  92. #if (_MSC_VER < 1400 ) && (!defined WINCE)
  93. // Microsoft Visual Studio 2003 and not WinCE.
  94. #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have.
  95. #else
  96. // Microsoft Visual Studio 2003 and earlier or WinCE.
  97. static inline int TIXML_VSCPRINTF( const char* format, va_list va )
  98. {
  99. int len = 512;
  100. for (;;) {
  101. len = len*2;
  102. char* str = new char[len]();
  103. const int required = _vsnprintf(str, len, format, va);
  104. delete[] str;
  105. if ( required != -1 ) {
  106. TIXMLASSERT( required >= 0 );
  107. len = required;
  108. break;
  109. }
  110. }
  111. TIXMLASSERT( len >= 0 );
  112. return len;
  113. }
  114. #endif
  115. #else
  116. // GCC version 3 and higher
  117. //#warning( "Using sn* functions." )
  118. #define TIXML_SNPRINTF snprintf
  119. #define TIXML_VSNPRINTF vsnprintf
  120. static inline int TIXML_VSCPRINTF( const char* format, va_list va )
  121. {
  122. int len = vsnprintf( 0, 0, format, va );
  123. TIXMLASSERT( len >= 0 );
  124. return len;
  125. }
  126. #define TIXML_SSCANF sscanf
  127. #endif
  128. #if defined(_WIN64)
  129. #define TIXML_FSEEK _fseeki64
  130. #define TIXML_FTELL _ftelli64
  131. #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__CYGWIN__)
  132. #define TIXML_FSEEK fseeko
  133. #define TIXML_FTELL ftello
  134. #elif defined(__ANDROID__) && __ANDROID_API__ > 24
  135. #define TIXML_FSEEK fseeko64
  136. #define TIXML_FTELL ftello64
  137. #else
  138. #define TIXML_FSEEK fseek
  139. #define TIXML_FTELL ftell
  140. #endif
  141. static const char LINE_FEED = static_cast<char>(0x0a); // all line endings are normalized to LF
  142. static const char LF = LINE_FEED;
  143. static const char CARRIAGE_RETURN = static_cast<char>(0x0d); // CR gets filtered out
  144. static const char CR = CARRIAGE_RETURN;
  145. static const char SINGLE_QUOTE = '\'';
  146. static const char DOUBLE_QUOTE = '\"';
  147. // Bunch of unicode info at:
  148. // http://www.unicode.org/faq/utf_bom.html
  149. // ef bb bf (Microsoft "lead bytes") - designates UTF-8
  150. static const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
  151. static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
  152. static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
  153. namespace tinyxml2
  154. {
  155. struct Entity {
  156. const char* pattern;
  157. int length;
  158. char value;
  159. };
  160. static const int NUM_ENTITIES = 5;
  161. static const Entity entities[NUM_ENTITIES] = {
  162. { "quot", 4, DOUBLE_QUOTE },
  163. { "amp", 3, '&' },
  164. { "apos", 4, SINGLE_QUOTE },
  165. { "lt", 2, '<' },
  166. { "gt", 2, '>' }
  167. };
  168. StrPair::~StrPair()
  169. {
  170. Reset();
  171. }
  172. void StrPair::TransferTo( StrPair* other )
  173. {
  174. if ( this == other ) {
  175. return;
  176. }
  177. // This in effect implements the assignment operator by "moving"
  178. // ownership (as in auto_ptr).
  179. TIXMLASSERT( other != 0 );
  180. TIXMLASSERT( other->_flags == 0 );
  181. TIXMLASSERT( other->_start == 0 );
  182. TIXMLASSERT( other->_end == 0 );
  183. other->Reset();
  184. other->_flags = _flags;
  185. other->_start = _start;
  186. other->_end = _end;
  187. _flags = 0;
  188. _start = 0;
  189. _end = 0;
  190. }
  191. void StrPair::Reset()
  192. {
  193. if ( _flags & NEEDS_DELETE ) {
  194. delete [] _start;
  195. }
  196. _flags = 0;
  197. _start = 0;
  198. _end = 0;
  199. }
  200. void StrPair::SetStr( const char* str, int flags )
  201. {
  202. TIXMLASSERT( str );
  203. Reset();
  204. size_t len = strlen( str );
  205. TIXMLASSERT( _start == 0 );
  206. _start = new char[ len+1 ];
  207. memcpy( _start, str, len+1 );
  208. _end = _start + len;
  209. _flags = flags | NEEDS_DELETE;
  210. }
  211. char* StrPair::ParseText( char* p, const char* endTag, int strFlags, int* curLineNumPtr )
  212. {
  213. TIXMLASSERT( p );
  214. TIXMLASSERT( endTag && *endTag );
  215. TIXMLASSERT(curLineNumPtr);
  216. char* start = p;
  217. const char endChar = *endTag;
  218. size_t length = strlen( endTag );
  219. // Inner loop of text parsing.
  220. while ( *p ) {
  221. if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) {
  222. Set( start, p, strFlags );
  223. return p + length;
  224. } else if (*p == '\n') {
  225. ++(*curLineNumPtr);
  226. }
  227. ++p;
  228. TIXMLASSERT( p );
  229. }
  230. return 0;
  231. }
  232. char* StrPair::ParseName( char* p )
  233. {
  234. if ( !p || !(*p) ) {
  235. return 0;
  236. }
  237. if ( !XMLUtil::IsNameStartChar( static_cast<unsigned char>(*p) ) ) {
  238. return 0;
  239. }
  240. char* const start = p;
  241. ++p;
  242. while ( *p && XMLUtil::IsNameChar( static_cast<unsigned char>(*p) ) ) {
  243. ++p;
  244. }
  245. Set( start, p, 0 );
  246. return p;
  247. }
  248. void StrPair::CollapseWhitespace()
  249. {
  250. // Adjusting _start would cause undefined behavior on delete[]
  251. TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 );
  252. // Trim leading space.
  253. _start = XMLUtil::SkipWhiteSpace( _start, 0 );
  254. if ( *_start ) {
  255. const char* p = _start; // the read pointer
  256. char* q = _start; // the write pointer
  257. while( *p ) {
  258. if ( XMLUtil::IsWhiteSpace( *p )) {
  259. p = XMLUtil::SkipWhiteSpace( p, 0 );
  260. if ( *p == 0 ) {
  261. break; // don't write to q; this trims the trailing space.
  262. }
  263. *q = ' ';
  264. ++q;
  265. }
  266. *q = *p;
  267. ++q;
  268. ++p;
  269. }
  270. *q = 0;
  271. }
  272. }
  273. const char* StrPair::GetStr()
  274. {
  275. TIXMLASSERT( _start );
  276. TIXMLASSERT( _end );
  277. if ( _flags & NEEDS_FLUSH ) {
  278. *_end = 0;
  279. _flags ^= NEEDS_FLUSH;
  280. if ( _flags ) {
  281. const char* p = _start; // the read pointer
  282. char* q = _start; // the write pointer
  283. while( p < _end ) {
  284. if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) {
  285. // CR-LF pair becomes LF
  286. // CR alone becomes LF
  287. // LF-CR becomes LF
  288. if ( *(p+1) == LF ) {
  289. p += 2;
  290. }
  291. else {
  292. ++p;
  293. }
  294. *q = LF;
  295. ++q;
  296. }
  297. else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) {
  298. if ( *(p+1) == CR ) {
  299. p += 2;
  300. }
  301. else {
  302. ++p;
  303. }
  304. *q = LF;
  305. ++q;
  306. }
  307. else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) {
  308. // Entities handled by tinyXML2:
  309. // - special entities in the entity table [in/out]
  310. // - numeric character reference [in]
  311. // &#20013; or &#x4e2d;
  312. if ( *(p+1) == '#' ) {
  313. const int buflen = 10;
  314. char buf[buflen] = { 0 };
  315. int len = 0;
  316. const char* adjusted = const_cast<char*>( XMLUtil::GetCharacterRef( p, buf, &len ) );
  317. if ( adjusted == 0 ) {
  318. *q = *p;
  319. ++p;
  320. ++q;
  321. }
  322. else {
  323. TIXMLASSERT( 0 <= len && len <= buflen );
  324. TIXMLASSERT( q + len <= adjusted );
  325. p = adjusted;
  326. memcpy( q, buf, len );
  327. q += len;
  328. }
  329. }
  330. else {
  331. bool entityFound = false;
  332. for( int i = 0; i < NUM_ENTITIES; ++i ) {
  333. const Entity& entity = entities[i];
  334. if ( strncmp( p + 1, entity.pattern, entity.length ) == 0
  335. && *( p + entity.length + 1 ) == ';' ) {
  336. // Found an entity - convert.
  337. *q = entity.value;
  338. ++q;
  339. p += entity.length + 2;
  340. entityFound = true;
  341. break;
  342. }
  343. }
  344. if ( !entityFound ) {
  345. // fixme: treat as error?
  346. ++p;
  347. ++q;
  348. }
  349. }
  350. }
  351. else {
  352. *q = *p;
  353. ++p;
  354. ++q;
  355. }
  356. }
  357. *q = 0;
  358. }
  359. // The loop below has plenty going on, and this
  360. // is a less useful mode. Break it out.
  361. if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) {
  362. CollapseWhitespace();
  363. }
  364. _flags = (_flags & NEEDS_DELETE);
  365. }
  366. TIXMLASSERT( _start );
  367. return _start;
  368. }
  369. // --------- XMLUtil ----------- //
  370. const char* XMLUtil::writeBoolTrue = "true";
  371. const char* XMLUtil::writeBoolFalse = "false";
  372. void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse)
  373. {
  374. static const char* defTrue = "true";
  375. static const char* defFalse = "false";
  376. writeBoolTrue = (writeTrue) ? writeTrue : defTrue;
  377. writeBoolFalse = (writeFalse) ? writeFalse : defFalse;
  378. }
  379. const char* XMLUtil::ReadBOM( const char* p, bool* bom )
  380. {
  381. TIXMLASSERT( p );
  382. TIXMLASSERT( bom );
  383. *bom = false;
  384. const unsigned char* pu = reinterpret_cast<const unsigned char*>(p);
  385. // Check for BOM:
  386. if ( *(pu+0) == TIXML_UTF_LEAD_0
  387. && *(pu+1) == TIXML_UTF_LEAD_1
  388. && *(pu+2) == TIXML_UTF_LEAD_2 ) {
  389. *bom = true;
  390. p += 3;
  391. }
  392. TIXMLASSERT( p );
  393. return p;
  394. }
  395. void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length )
  396. {
  397. const unsigned long BYTE_MASK = 0xBF;
  398. const unsigned long BYTE_MARK = 0x80;
  399. const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  400. if (input < 0x80) {
  401. *length = 1;
  402. }
  403. else if ( input < 0x800 ) {
  404. *length = 2;
  405. }
  406. else if ( input < 0x10000 ) {
  407. *length = 3;
  408. }
  409. else if ( input < 0x200000 ) {
  410. *length = 4;
  411. }
  412. else {
  413. *length = 0; // This code won't convert this correctly anyway.
  414. return;
  415. }
  416. output += *length;
  417. // Scary scary fall throughs are annotated with carefully designed comments
  418. // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc
  419. switch (*length) {
  420. case 4:
  421. --output;
  422. *output = static_cast<char>((input | BYTE_MARK) & BYTE_MASK);
  423. input >>= 6;
  424. TIXML_FALLTHROUGH;
  425. case 3:
  426. --output;
  427. *output = static_cast<char>((input | BYTE_MARK) & BYTE_MASK);
  428. input >>= 6;
  429. TIXML_FALLTHROUGH;
  430. case 2:
  431. --output;
  432. *output = static_cast<char>((input | BYTE_MARK) & BYTE_MASK);
  433. input >>= 6;
  434. TIXML_FALLTHROUGH;
  435. case 1:
  436. --output;
  437. *output = static_cast<char>(input | FIRST_BYTE_MARK[*length]);
  438. break;
  439. default:
  440. TIXMLASSERT( false );
  441. }
  442. }
  443. const char* XMLUtil::GetCharacterRef(const char* p, char* value, int* length)
  444. {
  445. // Assume an entity, and pull it out.
  446. *length = 0;
  447. static const uint32_t MAX_CODE_POINT = 0x10FFFF;
  448. if (*(p + 1) == '#' && *(p + 2)) {
  449. uint32_t ucs = 0;
  450. ptrdiff_t delta = 0;
  451. uint32_t mult = 1;
  452. static const char SEMICOLON = ';';
  453. bool hex = false;
  454. uint32_t radix = 10;
  455. const char* q = 0;
  456. char terminator = '#';
  457. if (*(p + 2) == 'x') {
  458. // Hexadecimal.
  459. hex = true;
  460. radix = 16;
  461. terminator = 'x';
  462. q = p + 3;
  463. }
  464. else {
  465. // Decimal.
  466. q = p + 2;
  467. }
  468. if (!(*q)) {
  469. return 0;
  470. }
  471. q = strchr(q, SEMICOLON);
  472. if (!q) {
  473. return 0;
  474. }
  475. TIXMLASSERT(*q == SEMICOLON);
  476. delta = q - p;
  477. --q;
  478. while (*q != terminator) {
  479. uint32_t digit = 0;
  480. if (*q >= '0' && *q <= '9') {
  481. digit = *q - '0';
  482. }
  483. else if (hex && (*q >= 'a' && *q <= 'f')) {
  484. digit = *q - 'a' + 10;
  485. }
  486. else if (hex && (*q >= 'A' && *q <= 'F')) {
  487. digit = *q - 'A' + 10;
  488. }
  489. else {
  490. return 0;
  491. }
  492. TIXMLASSERT(digit < radix);
  493. const unsigned int digitScaled = mult * digit;
  494. ucs += digitScaled;
  495. mult *= radix;
  496. // Security check: could a value exist that is out of range?
  497. // Easily; limit to the MAX_CODE_POINT, which also allows for a
  498. // bunch of leading zeroes.
  499. if (mult > MAX_CODE_POINT) {
  500. mult = MAX_CODE_POINT;
  501. }
  502. --q;
  503. }
  504. // Out of range:
  505. if (ucs > MAX_CODE_POINT) {
  506. return 0;
  507. }
  508. // convert the UCS to UTF-8
  509. ConvertUTF32ToUTF8(ucs, value, length);
  510. if (length == 0) {
  511. // If length is 0, there was an error. (Security? Bad input?)
  512. // Fail safely.
  513. return 0;
  514. }
  515. return p + delta + 1;
  516. }
  517. return p + 1;
  518. }
  519. void XMLUtil::ToStr( int v, char* buffer, int bufferSize )
  520. {
  521. TIXML_SNPRINTF( buffer, bufferSize, "%d", v );
  522. }
  523. void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize )
  524. {
  525. TIXML_SNPRINTF( buffer, bufferSize, "%u", v );
  526. }
  527. void XMLUtil::ToStr( bool v, char* buffer, int bufferSize )
  528. {
  529. TIXML_SNPRINTF( buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse);
  530. }
  531. /*
  532. ToStr() of a number is a very tricky topic.
  533. https://github.com/leethomason/tinyxml2/issues/106
  534. */
  535. void XMLUtil::ToStr( float v, char* buffer, int bufferSize )
  536. {
  537. TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v );
  538. }
  539. void XMLUtil::ToStr( double v, char* buffer, int bufferSize )
  540. {
  541. TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v );
  542. }
  543. void XMLUtil::ToStr( int64_t v, char* buffer, int bufferSize )
  544. {
  545. // horrible syntax trick to make the compiler happy about %lld
  546. TIXML_SNPRINTF(buffer, bufferSize, "%lld", static_cast<long long>(v));
  547. }
  548. void XMLUtil::ToStr( uint64_t v, char* buffer, int bufferSize )
  549. {
  550. // horrible syntax trick to make the compiler happy about %llu
  551. TIXML_SNPRINTF(buffer, bufferSize, "%llu", static_cast<unsigned long long>(v));
  552. }
  553. bool XMLUtil::ToInt(const char* str, int* value)
  554. {
  555. if (IsPrefixHex(str)) {
  556. unsigned v;
  557. if (TIXML_SSCANF(str, "%x", &v) == 1) {
  558. *value = static_cast<int>(v);
  559. return true;
  560. }
  561. }
  562. else {
  563. if (TIXML_SSCANF(str, "%d", value) == 1) {
  564. return true;
  565. }
  566. }
  567. return false;
  568. }
  569. bool XMLUtil::ToUnsigned(const char* str, unsigned* value)
  570. {
  571. if (TIXML_SSCANF(str, IsPrefixHex(str) ? "%x" : "%u", value) == 1) {
  572. return true;
  573. }
  574. return false;
  575. }
  576. bool XMLUtil::ToBool( const char* str, bool* value )
  577. {
  578. int ival = 0;
  579. if ( ToInt( str, &ival )) {
  580. *value = (ival==0) ? false : true;
  581. return true;
  582. }
  583. static const char* TRUE_VALS[] = { "true", "True", "TRUE", 0 };
  584. static const char* FALSE_VALS[] = { "false", "False", "FALSE", 0 };
  585. for (int i = 0; TRUE_VALS[i]; ++i) {
  586. if (StringEqual(str, TRUE_VALS[i])) {
  587. *value = true;
  588. return true;
  589. }
  590. }
  591. for (int i = 0; FALSE_VALS[i]; ++i) {
  592. if (StringEqual(str, FALSE_VALS[i])) {
  593. *value = false;
  594. return true;
  595. }
  596. }
  597. return false;
  598. }
  599. bool XMLUtil::ToFloat( const char* str, float* value )
  600. {
  601. if ( TIXML_SSCANF( str, "%f", value ) == 1 ) {
  602. return true;
  603. }
  604. return false;
  605. }
  606. bool XMLUtil::ToDouble( const char* str, double* value )
  607. {
  608. if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) {
  609. return true;
  610. }
  611. return false;
  612. }
  613. bool XMLUtil::ToInt64(const char* str, int64_t* value)
  614. {
  615. if (IsPrefixHex(str)) {
  616. unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llx
  617. if (TIXML_SSCANF(str, "%llx", &v) == 1) {
  618. *value = static_cast<int64_t>(v);
  619. return true;
  620. }
  621. }
  622. else {
  623. long long v = 0; // horrible syntax trick to make the compiler happy about %lld
  624. if (TIXML_SSCANF(str, "%lld", &v) == 1) {
  625. *value = static_cast<int64_t>(v);
  626. return true;
  627. }
  628. }
  629. return false;
  630. }
  631. bool XMLUtil::ToUnsigned64(const char* str, uint64_t* value) {
  632. unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llu
  633. if(TIXML_SSCANF(str, IsPrefixHex(str) ? "%llx" : "%llu", &v) == 1) {
  634. *value = static_cast<uint64_t>(v);
  635. return true;
  636. }
  637. return false;
  638. }
  639. char* XMLDocument::Identify( char* p, XMLNode** node, bool first )
  640. {
  641. TIXMLASSERT( node );
  642. TIXMLASSERT( p );
  643. char* const start = p;
  644. int const startLine = _parseCurLineNum;
  645. p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum );
  646. if( !*p ) {
  647. *node = 0;
  648. TIXMLASSERT( p );
  649. return p;
  650. }
  651. // These strings define the matching patterns:
  652. static const char* xmlHeader = { "<?" };
  653. static const char* commentHeader = { "<!--" };
  654. static const char* cdataHeader = { "<![CDATA[" };
  655. static const char* dtdHeader = { "<!" };
  656. static const char* elementHeader = { "<" }; // and a header for everything else; check last.
  657. static const int xmlHeaderLen = 2;
  658. static const int commentHeaderLen = 4;
  659. static const int cdataHeaderLen = 9;
  660. static const int dtdHeaderLen = 2;
  661. static const int elementHeaderLen = 1;
  662. TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLUnknown ) ); // use same memory pool
  663. TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLDeclaration ) ); // use same memory pool
  664. XMLNode* returnNode = 0;
  665. if ( XMLUtil::StringEqual( p, xmlHeader, xmlHeaderLen ) ) {
  666. returnNode = CreateUnlinkedNode<XMLDeclaration>( _commentPool );
  667. returnNode->_parseLineNum = _parseCurLineNum;
  668. p += xmlHeaderLen;
  669. }
  670. else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) {
  671. returnNode = CreateUnlinkedNode<XMLComment>( _commentPool );
  672. returnNode->_parseLineNum = _parseCurLineNum;
  673. p += commentHeaderLen;
  674. }
  675. else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) {
  676. XMLText* text = CreateUnlinkedNode<XMLText>( _textPool );
  677. returnNode = text;
  678. returnNode->_parseLineNum = _parseCurLineNum;
  679. p += cdataHeaderLen;
  680. text->SetCData( true );
  681. }
  682. else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) {
  683. returnNode = CreateUnlinkedNode<XMLUnknown>( _commentPool );
  684. returnNode->_parseLineNum = _parseCurLineNum;
  685. p += dtdHeaderLen;
  686. }
  687. else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) {
  688. // Preserve whitespace pedantically before closing tag, when it's immediately after opening tag
  689. if (WhitespaceMode() == PEDANTIC_WHITESPACE && first && p != start && *(p + elementHeaderLen) == '/') {
  690. returnNode = CreateUnlinkedNode<XMLText>(_textPool);
  691. returnNode->_parseLineNum = startLine;
  692. p = start; // Back it up, all the text counts.
  693. _parseCurLineNum = startLine;
  694. }
  695. else {
  696. returnNode = CreateUnlinkedNode<XMLElement>(_elementPool);
  697. returnNode->_parseLineNum = _parseCurLineNum;
  698. p += elementHeaderLen;
  699. }
  700. }
  701. else {
  702. returnNode = CreateUnlinkedNode<XMLText>( _textPool );
  703. returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character
  704. p = start; // Back it up, all the text counts.
  705. _parseCurLineNum = startLine;
  706. }
  707. TIXMLASSERT( returnNode );
  708. TIXMLASSERT( p );
  709. *node = returnNode;
  710. return p;
  711. }
  712. bool XMLDocument::Accept( XMLVisitor* visitor ) const
  713. {
  714. TIXMLASSERT( visitor );
  715. if ( visitor->VisitEnter( *this ) ) {
  716. for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) {
  717. if ( !node->Accept( visitor ) ) {
  718. break;
  719. }
  720. }
  721. }
  722. return visitor->VisitExit( *this );
  723. }
  724. // --------- XMLNode ----------- //
  725. XMLNode::XMLNode( XMLDocument* doc ) :
  726. _document( doc ),
  727. _parent( 0 ),
  728. _value(),
  729. _parseLineNum( 0 ),
  730. _firstChild( 0 ), _lastChild( 0 ),
  731. _prev( 0 ), _next( 0 ),
  732. _userData( 0 ),
  733. _memPool( 0 )
  734. {
  735. }
  736. XMLNode::~XMLNode()
  737. {
  738. DeleteChildren();
  739. if ( _parent ) {
  740. _parent->Unlink( this );
  741. }
  742. }
  743. // ChildElementCount was originally suggested by msteiger on the sourceforge page for TinyXML and modified by KB1SPH for TinyXML-2.
  744. int XMLNode::ChildElementCount(const char *value) const {
  745. int count = 0;
  746. const XMLElement *e = FirstChildElement(value);
  747. while (e) {
  748. e = e->NextSiblingElement(value);
  749. count++;
  750. }
  751. return count;
  752. }
  753. int XMLNode::ChildElementCount() const {
  754. int count = 0;
  755. const XMLElement *e = FirstChildElement();
  756. while (e) {
  757. e = e->NextSiblingElement();
  758. count++;
  759. }
  760. return count;
  761. }
  762. const char* XMLNode::Value() const
  763. {
  764. // Edge case: XMLDocuments don't have a Value. Return null.
  765. if ( this->ToDocument() )
  766. return 0;
  767. return _value.GetStr();
  768. }
  769. void XMLNode::SetValue( const char* str, bool staticMem )
  770. {
  771. if ( staticMem ) {
  772. _value.SetInternedStr( str );
  773. }
  774. else {
  775. _value.SetStr( str );
  776. }
  777. }
  778. XMLNode* XMLNode::DeepClone(XMLDocument* target) const
  779. {
  780. XMLNode* clone = this->ShallowClone(target);
  781. if (!clone) return 0;
  782. for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) {
  783. XMLNode* childClone = child->DeepClone(target);
  784. TIXMLASSERT(childClone);
  785. clone->InsertEndChild(childClone);
  786. }
  787. return clone;
  788. }
  789. void XMLNode::DeleteChildren()
  790. {
  791. while( _firstChild ) {
  792. TIXMLASSERT( _lastChild );
  793. DeleteChild( _firstChild );
  794. }
  795. _firstChild = _lastChild = 0;
  796. }
  797. void XMLNode::Unlink( XMLNode* child )
  798. {
  799. TIXMLASSERT( child );
  800. TIXMLASSERT( child->_document == _document );
  801. TIXMLASSERT( child->_parent == this );
  802. if ( child == _firstChild ) {
  803. _firstChild = _firstChild->_next;
  804. }
  805. if ( child == _lastChild ) {
  806. _lastChild = _lastChild->_prev;
  807. }
  808. if ( child->_prev ) {
  809. child->_prev->_next = child->_next;
  810. }
  811. if ( child->_next ) {
  812. child->_next->_prev = child->_prev;
  813. }
  814. child->_next = 0;
  815. child->_prev = 0;
  816. child->_parent = 0;
  817. }
  818. void XMLNode::DeleteChild( XMLNode* node )
  819. {
  820. TIXMLASSERT( node );
  821. TIXMLASSERT( node->_document == _document );
  822. TIXMLASSERT( node->_parent == this );
  823. Unlink( node );
  824. TIXMLASSERT(node->_prev == 0);
  825. TIXMLASSERT(node->_next == 0);
  826. TIXMLASSERT(node->_parent == 0);
  827. DeleteNode( node );
  828. }
  829. XMLNode* XMLNode::InsertEndChild( XMLNode* addThis )
  830. {
  831. TIXMLASSERT( addThis );
  832. if ( addThis->_document != _document ) {
  833. TIXMLASSERT( false );
  834. return 0;
  835. }
  836. InsertChildPreamble( addThis );
  837. if ( _lastChild ) {
  838. TIXMLASSERT( _firstChild );
  839. TIXMLASSERT( _lastChild->_next == 0 );
  840. _lastChild->_next = addThis;
  841. addThis->_prev = _lastChild;
  842. _lastChild = addThis;
  843. addThis->_next = 0;
  844. }
  845. else {
  846. TIXMLASSERT( _firstChild == 0 );
  847. _firstChild = _lastChild = addThis;
  848. addThis->_prev = 0;
  849. addThis->_next = 0;
  850. }
  851. addThis->_parent = this;
  852. return addThis;
  853. }
  854. XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis )
  855. {
  856. TIXMLASSERT( addThis );
  857. if ( addThis->_document != _document ) {
  858. TIXMLASSERT( false );
  859. return 0;
  860. }
  861. InsertChildPreamble( addThis );
  862. if ( _firstChild ) {
  863. TIXMLASSERT( _lastChild );
  864. TIXMLASSERT( _firstChild->_prev == 0 );
  865. _firstChild->_prev = addThis;
  866. addThis->_next = _firstChild;
  867. _firstChild = addThis;
  868. addThis->_prev = 0;
  869. }
  870. else {
  871. TIXMLASSERT( _lastChild == 0 );
  872. _firstChild = _lastChild = addThis;
  873. addThis->_prev = 0;
  874. addThis->_next = 0;
  875. }
  876. addThis->_parent = this;
  877. return addThis;
  878. }
  879. XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis )
  880. {
  881. TIXMLASSERT( addThis );
  882. if ( addThis->_document != _document ) {
  883. TIXMLASSERT( false );
  884. return 0;
  885. }
  886. TIXMLASSERT( afterThis );
  887. if ( afterThis->_parent != this ) {
  888. TIXMLASSERT( false );
  889. return 0;
  890. }
  891. if ( afterThis == addThis ) {
  892. // Current state: BeforeThis -> AddThis -> OneAfterAddThis
  893. // Now AddThis must disappear from it's location and then
  894. // reappear between BeforeThis and OneAfterAddThis.
  895. // So just leave it where it is.
  896. return addThis;
  897. }
  898. if ( afterThis->_next == 0 ) {
  899. // The last node or the only node.
  900. return InsertEndChild( addThis );
  901. }
  902. InsertChildPreamble( addThis );
  903. addThis->_prev = afterThis;
  904. addThis->_next = afterThis->_next;
  905. afterThis->_next->_prev = addThis;
  906. afterThis->_next = addThis;
  907. addThis->_parent = this;
  908. return addThis;
  909. }
  910. const XMLElement* XMLNode::FirstChildElement( const char* name ) const
  911. {
  912. for( const XMLNode* node = _firstChild; node; node = node->_next ) {
  913. const XMLElement* element = node->ToElementWithName( name );
  914. if ( element ) {
  915. return element;
  916. }
  917. }
  918. return 0;
  919. }
  920. const XMLElement* XMLNode::LastChildElement( const char* name ) const
  921. {
  922. for( const XMLNode* node = _lastChild; node; node = node->_prev ) {
  923. const XMLElement* element = node->ToElementWithName( name );
  924. if ( element ) {
  925. return element;
  926. }
  927. }
  928. return 0;
  929. }
  930. const XMLElement* XMLNode::NextSiblingElement( const char* name ) const
  931. {
  932. for( const XMLNode* node = _next; node; node = node->_next ) {
  933. const XMLElement* element = node->ToElementWithName( name );
  934. if ( element ) {
  935. return element;
  936. }
  937. }
  938. return 0;
  939. }
  940. const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const
  941. {
  942. for( const XMLNode* node = _prev; node; node = node->_prev ) {
  943. const XMLElement* element = node->ToElementWithName( name );
  944. if ( element ) {
  945. return element;
  946. }
  947. }
  948. return 0;
  949. }
  950. char* XMLNode::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr )
  951. {
  952. // This is a recursive method, but thinking about it "at the current level"
  953. // it is a pretty simple flat list:
  954. // <foo/>
  955. // <!-- comment -->
  956. //
  957. // With a special case:
  958. // <foo>
  959. // </foo>
  960. // <!-- comment -->
  961. //
  962. // Where the closing element (/foo) *must* be the next thing after the opening
  963. // element, and the names must match. BUT the tricky bit is that the closing
  964. // element will be read by the child.
  965. //
  966. // 'endTag' is the end tag for this node, it is returned by a call to a child.
  967. // 'parentEnd' is the end tag for the parent, which is filled in and returned.
  968. XMLDocument::DepthTracker tracker(_document);
  969. if (_document->Error())
  970. return 0;
  971. bool first = true;
  972. while( p && *p ) {
  973. XMLNode* node = 0;
  974. p = _document->Identify( p, &node, first );
  975. TIXMLASSERT( p );
  976. if ( node == 0 ) {
  977. break;
  978. }
  979. first = false;
  980. const int initialLineNum = node->_parseLineNum;
  981. StrPair endTag;
  982. p = node->ParseDeep( p, &endTag, curLineNumPtr );
  983. if ( !p ) {
  984. _document->DeleteNode( node );
  985. if ( !_document->Error() ) {
  986. _document->SetError( XML_ERROR_PARSING, initialLineNum, 0);
  987. }
  988. break;
  989. }
  990. const XMLDeclaration* const decl = node->ToDeclaration();
  991. if ( decl ) {
  992. // Declarations are only allowed at document level
  993. //
  994. // Multiple declarations are allowed but all declarations
  995. // must occur before anything else.
  996. //
  997. // Optimized due to a security test case. If the first node is
  998. // a declaration, and the last node is a declaration, then only
  999. // declarations have so far been added.
  1000. bool wellLocated = false;
  1001. if (ToDocument()) {
  1002. if (FirstChild()) {
  1003. wellLocated =
  1004. FirstChild() &&
  1005. FirstChild()->ToDeclaration() &&
  1006. LastChild() &&
  1007. LastChild()->ToDeclaration();
  1008. }
  1009. else {
  1010. wellLocated = true;
  1011. }
  1012. }
  1013. if ( !wellLocated ) {
  1014. _document->SetError( XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value());
  1015. _document->DeleteNode( node );
  1016. break;
  1017. }
  1018. }
  1019. XMLElement* ele = node->ToElement();
  1020. if ( ele ) {
  1021. // We read the end tag. Return it to the parent.
  1022. if ( ele->ClosingType() == XMLElement::CLOSING ) {
  1023. if ( parentEndTag ) {
  1024. ele->_value.TransferTo( parentEndTag );
  1025. }
  1026. node->_memPool->SetTracked(); // created and then immediately deleted.
  1027. DeleteNode( node );
  1028. return p;
  1029. }
  1030. // Handle an end tag returned to this level.
  1031. // And handle a bunch of annoying errors.
  1032. bool mismatch = false;
  1033. if ( endTag.Empty() ) {
  1034. if ( ele->ClosingType() == XMLElement::OPEN ) {
  1035. mismatch = true;
  1036. }
  1037. }
  1038. else {
  1039. if ( ele->ClosingType() != XMLElement::OPEN ) {
  1040. mismatch = true;
  1041. }
  1042. else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) {
  1043. mismatch = true;
  1044. }
  1045. }
  1046. if ( mismatch ) {
  1047. _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name());
  1048. _document->DeleteNode( node );
  1049. break;
  1050. }
  1051. }
  1052. InsertEndChild( node );
  1053. }
  1054. return 0;
  1055. }
  1056. /*static*/ void XMLNode::DeleteNode( XMLNode* node )
  1057. {
  1058. if ( node == 0 ) {
  1059. return;
  1060. }
  1061. TIXMLASSERT(node->_document);
  1062. if (!node->ToDocument()) {
  1063. node->_document->MarkInUse(node);
  1064. }
  1065. MemPool* pool = node->_memPool;
  1066. node->~XMLNode();
  1067. pool->Free( node );
  1068. }
  1069. void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const
  1070. {
  1071. TIXMLASSERT( insertThis );
  1072. TIXMLASSERT( insertThis->_document == _document );
  1073. if (insertThis->_parent) {
  1074. insertThis->_parent->Unlink( insertThis );
  1075. }
  1076. else {
  1077. insertThis->_document->MarkInUse(insertThis);
  1078. insertThis->_memPool->SetTracked();
  1079. }
  1080. }
  1081. const XMLElement* XMLNode::ToElementWithName( const char* name ) const
  1082. {
  1083. const XMLElement* element = this->ToElement();
  1084. if ( element == 0 ) {
  1085. return 0;
  1086. }
  1087. if ( name == 0 ) {
  1088. return element;
  1089. }
  1090. if ( XMLUtil::StringEqual( element->Name(), name ) ) {
  1091. return element;
  1092. }
  1093. return 0;
  1094. }
  1095. // --------- XMLText ---------- //
  1096. char* XMLText::ParseDeep( char* p, StrPair*, int* curLineNumPtr )
  1097. {
  1098. if ( this->CData() ) {
  1099. p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr );
  1100. if ( !p ) {
  1101. _document->SetError( XML_ERROR_PARSING_CDATA, _parseLineNum, 0 );
  1102. }
  1103. return p;
  1104. }
  1105. else {
  1106. int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES;
  1107. if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) {
  1108. flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING;
  1109. }
  1110. p = _value.ParseText( p, "<", flags, curLineNumPtr );
  1111. if ( p && *p ) {
  1112. return p-1;
  1113. }
  1114. if ( !p ) {
  1115. _document->SetError( XML_ERROR_PARSING_TEXT, _parseLineNum, 0 );
  1116. }
  1117. }
  1118. return 0;
  1119. }
  1120. XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const
  1121. {
  1122. if ( !doc ) {
  1123. doc = _document;
  1124. }
  1125. XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern?
  1126. text->SetCData( this->CData() );
  1127. return text;
  1128. }
  1129. bool XMLText::ShallowEqual( const XMLNode* compare ) const
  1130. {
  1131. TIXMLASSERT( compare );
  1132. const XMLText* text = compare->ToText();
  1133. return ( text && XMLUtil::StringEqual( text->Value(), Value() ) );
  1134. }
  1135. bool XMLText::Accept( XMLVisitor* visitor ) const
  1136. {
  1137. TIXMLASSERT( visitor );
  1138. return visitor->Visit( *this );
  1139. }
  1140. // --------- XMLComment ---------- //
  1141. XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc )
  1142. {
  1143. }
  1144. XMLComment::~XMLComment()
  1145. {
  1146. }
  1147. char* XMLComment::ParseDeep( char* p, StrPair*, int* curLineNumPtr )
  1148. {
  1149. // Comment parses as text.
  1150. p = _value.ParseText( p, "-->", StrPair::COMMENT, curLineNumPtr );
  1151. if ( p == 0 ) {
  1152. _document->SetError( XML_ERROR_PARSING_COMMENT, _parseLineNum, 0 );
  1153. }
  1154. return p;
  1155. }
  1156. XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const
  1157. {
  1158. if ( !doc ) {
  1159. doc = _document;
  1160. }
  1161. XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern?
  1162. return comment;
  1163. }
  1164. bool XMLComment::ShallowEqual( const XMLNode* compare ) const
  1165. {
  1166. TIXMLASSERT( compare );
  1167. const XMLComment* comment = compare->ToComment();
  1168. return ( comment && XMLUtil::StringEqual( comment->Value(), Value() ));
  1169. }
  1170. bool XMLComment::Accept( XMLVisitor* visitor ) const
  1171. {
  1172. TIXMLASSERT( visitor );
  1173. return visitor->Visit( *this );
  1174. }
  1175. // --------- XMLDeclaration ---------- //
  1176. XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc )
  1177. {
  1178. }
  1179. XMLDeclaration::~XMLDeclaration()
  1180. {
  1181. //printf( "~XMLDeclaration\n" );
  1182. }
  1183. char* XMLDeclaration::ParseDeep( char* p, StrPair*, int* curLineNumPtr )
  1184. {
  1185. // Declaration parses as text.
  1186. p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr );
  1187. if ( p == 0 ) {
  1188. _document->SetError( XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0 );
  1189. }
  1190. return p;
  1191. }
  1192. XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const
  1193. {
  1194. if ( !doc ) {
  1195. doc = _document;
  1196. }
  1197. XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern?
  1198. return dec;
  1199. }
  1200. bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const
  1201. {
  1202. TIXMLASSERT( compare );
  1203. const XMLDeclaration* declaration = compare->ToDeclaration();
  1204. return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() ));
  1205. }
  1206. bool XMLDeclaration::Accept( XMLVisitor* visitor ) const
  1207. {
  1208. TIXMLASSERT( visitor );
  1209. return visitor->Visit( *this );
  1210. }
  1211. // --------- XMLUnknown ---------- //
  1212. XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc )
  1213. {
  1214. }
  1215. XMLUnknown::~XMLUnknown()
  1216. {
  1217. }
  1218. char* XMLUnknown::ParseDeep( char* p, StrPair*, int* curLineNumPtr )
  1219. {
  1220. // Unknown parses as text.
  1221. p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr );
  1222. if ( !p ) {
  1223. _document->SetError( XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0 );
  1224. }
  1225. return p;
  1226. }
  1227. XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const
  1228. {
  1229. if ( !doc ) {
  1230. doc = _document;
  1231. }
  1232. XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern?
  1233. return text;
  1234. }
  1235. bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const
  1236. {
  1237. TIXMLASSERT( compare );
  1238. const XMLUnknown* unknown = compare->ToUnknown();
  1239. return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() ));
  1240. }
  1241. bool XMLUnknown::Accept( XMLVisitor* visitor ) const
  1242. {
  1243. TIXMLASSERT( visitor );
  1244. return visitor->Visit( *this );
  1245. }
  1246. // --------- XMLAttribute ---------- //
  1247. const char* XMLAttribute::Name() const
  1248. {
  1249. return _name.GetStr();
  1250. }
  1251. const char* XMLAttribute::Value() const
  1252. {
  1253. return _value.GetStr();
  1254. }
  1255. char* XMLAttribute::ParseDeep( char* p, bool processEntities, int* curLineNumPtr )
  1256. {
  1257. // Parse using the name rules: bug fix, was using ParseText before
  1258. p = _name.ParseName( p );
  1259. if ( !p || !*p ) {
  1260. return 0;
  1261. }
  1262. // Skip white space before =
  1263. p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr );
  1264. if ( *p != '=' ) {
  1265. return 0;
  1266. }
  1267. ++p; // move up to opening quote
  1268. p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr );
  1269. if ( *p != '\"' && *p != '\'' ) {
  1270. return 0;
  1271. }
  1272. const char endTag[2] = { *p, 0 };
  1273. ++p; // move past opening quote
  1274. p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr );
  1275. return p;
  1276. }
  1277. void XMLAttribute::SetName( const char* n )
  1278. {
  1279. _name.SetStr( n );
  1280. }
  1281. XMLError XMLAttribute::QueryIntValue( int* value ) const
  1282. {
  1283. if ( XMLUtil::ToInt( Value(), value )) {
  1284. return XML_SUCCESS;
  1285. }
  1286. return XML_WRONG_ATTRIBUTE_TYPE;
  1287. }
  1288. XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const
  1289. {
  1290. if ( XMLUtil::ToUnsigned( Value(), value )) {
  1291. return XML_SUCCESS;
  1292. }
  1293. return XML_WRONG_ATTRIBUTE_TYPE;
  1294. }
  1295. XMLError XMLAttribute::QueryInt64Value(int64_t* value) const
  1296. {
  1297. if (XMLUtil::ToInt64(Value(), value)) {
  1298. return XML_SUCCESS;
  1299. }
  1300. return XML_WRONG_ATTRIBUTE_TYPE;
  1301. }
  1302. XMLError XMLAttribute::QueryUnsigned64Value(uint64_t* value) const
  1303. {
  1304. if(XMLUtil::ToUnsigned64(Value(), value)) {
  1305. return XML_SUCCESS;
  1306. }
  1307. return XML_WRONG_ATTRIBUTE_TYPE;
  1308. }
  1309. XMLError XMLAttribute::QueryBoolValue( bool* value ) const
  1310. {
  1311. if ( XMLUtil::ToBool( Value(), value )) {
  1312. return XML_SUCCESS;
  1313. }
  1314. return XML_WRONG_ATTRIBUTE_TYPE;
  1315. }
  1316. XMLError XMLAttribute::QueryFloatValue( float* value ) const
  1317. {
  1318. if ( XMLUtil::ToFloat( Value(), value )) {
  1319. return XML_SUCCESS;
  1320. }
  1321. return XML_WRONG_ATTRIBUTE_TYPE;
  1322. }
  1323. XMLError XMLAttribute::QueryDoubleValue( double* value ) const
  1324. {
  1325. if ( XMLUtil::ToDouble( Value(), value )) {
  1326. return XML_SUCCESS;
  1327. }
  1328. return XML_WRONG_ATTRIBUTE_TYPE;
  1329. }
  1330. void XMLAttribute::SetAttribute( const char* v )
  1331. {
  1332. _value.SetStr( v );
  1333. }
  1334. void XMLAttribute::SetAttribute( int v )
  1335. {
  1336. char buf[BUF_SIZE];
  1337. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1338. _value.SetStr( buf );
  1339. }
  1340. void XMLAttribute::SetAttribute( unsigned v )
  1341. {
  1342. char buf[BUF_SIZE];
  1343. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1344. _value.SetStr( buf );
  1345. }
  1346. void XMLAttribute::SetAttribute(int64_t v)
  1347. {
  1348. char buf[BUF_SIZE];
  1349. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1350. _value.SetStr(buf);
  1351. }
  1352. void XMLAttribute::SetAttribute(uint64_t v)
  1353. {
  1354. char buf[BUF_SIZE];
  1355. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1356. _value.SetStr(buf);
  1357. }
  1358. void XMLAttribute::SetAttribute( bool v )
  1359. {
  1360. char buf[BUF_SIZE];
  1361. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1362. _value.SetStr( buf );
  1363. }
  1364. void XMLAttribute::SetAttribute( double v )
  1365. {
  1366. char buf[BUF_SIZE];
  1367. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1368. _value.SetStr( buf );
  1369. }
  1370. void XMLAttribute::SetAttribute( float v )
  1371. {
  1372. char buf[BUF_SIZE];
  1373. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1374. _value.SetStr( buf );
  1375. }
  1376. // --------- XMLElement ---------- //
  1377. XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ),
  1378. _closingType( OPEN ),
  1379. _rootAttribute( 0 )
  1380. {
  1381. }
  1382. XMLElement::~XMLElement()
  1383. {
  1384. while( _rootAttribute ) {
  1385. XMLAttribute* next = _rootAttribute->_next;
  1386. DeleteAttribute( _rootAttribute );
  1387. _rootAttribute = next;
  1388. }
  1389. }
  1390. const XMLAttribute* XMLElement::FindAttribute( const char* name ) const
  1391. {
  1392. for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) {
  1393. if ( XMLUtil::StringEqual( a->Name(), name ) ) {
  1394. return a;
  1395. }
  1396. }
  1397. return 0;
  1398. }
  1399. const char* XMLElement::Attribute( const char* name, const char* value ) const
  1400. {
  1401. const XMLAttribute* a = FindAttribute( name );
  1402. if ( !a ) {
  1403. return 0;
  1404. }
  1405. if ( !value || XMLUtil::StringEqual( a->Value(), value )) {
  1406. return a->Value();
  1407. }
  1408. return 0;
  1409. }
  1410. int XMLElement::IntAttribute(const char* name, int defaultValue) const
  1411. {
  1412. int i = defaultValue;
  1413. QueryIntAttribute(name, &i);
  1414. return i;
  1415. }
  1416. unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const
  1417. {
  1418. unsigned i = defaultValue;
  1419. QueryUnsignedAttribute(name, &i);
  1420. return i;
  1421. }
  1422. int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const
  1423. {
  1424. int64_t i = defaultValue;
  1425. QueryInt64Attribute(name, &i);
  1426. return i;
  1427. }
  1428. uint64_t XMLElement::Unsigned64Attribute(const char* name, uint64_t defaultValue) const
  1429. {
  1430. uint64_t i = defaultValue;
  1431. QueryUnsigned64Attribute(name, &i);
  1432. return i;
  1433. }
  1434. bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const
  1435. {
  1436. bool b = defaultValue;
  1437. QueryBoolAttribute(name, &b);
  1438. return b;
  1439. }
  1440. double XMLElement::DoubleAttribute(const char* name, double defaultValue) const
  1441. {
  1442. double d = defaultValue;
  1443. QueryDoubleAttribute(name, &d);
  1444. return d;
  1445. }
  1446. float XMLElement::FloatAttribute(const char* name, float defaultValue) const
  1447. {
  1448. float f = defaultValue;
  1449. QueryFloatAttribute(name, &f);
  1450. return f;
  1451. }
  1452. const char* XMLElement::GetText() const
  1453. {
  1454. /* skip comment node */
  1455. const XMLNode* node = FirstChild();
  1456. while (node) {
  1457. if (node->ToComment()) {
  1458. node = node->NextSibling();
  1459. continue;
  1460. }
  1461. break;
  1462. }
  1463. if ( node && node->ToText() ) {
  1464. return node->Value();
  1465. }
  1466. return 0;
  1467. }
  1468. void XMLElement::SetText( const char* inText )
  1469. {
  1470. if ( FirstChild() && FirstChild()->ToText() )
  1471. FirstChild()->SetValue( inText );
  1472. else {
  1473. XMLText* theText = GetDocument()->NewText( inText );
  1474. InsertFirstChild( theText );
  1475. }
  1476. }
  1477. void XMLElement::SetText( int v )
  1478. {
  1479. char buf[BUF_SIZE];
  1480. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1481. SetText( buf );
  1482. }
  1483. void XMLElement::SetText( unsigned v )
  1484. {
  1485. char buf[BUF_SIZE];
  1486. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1487. SetText( buf );
  1488. }
  1489. void XMLElement::SetText(int64_t v)
  1490. {
  1491. char buf[BUF_SIZE];
  1492. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1493. SetText(buf);
  1494. }
  1495. void XMLElement::SetText(uint64_t v) {
  1496. char buf[BUF_SIZE];
  1497. XMLUtil::ToStr(v, buf, BUF_SIZE);
  1498. SetText(buf);
  1499. }
  1500. void XMLElement::SetText( bool v )
  1501. {
  1502. char buf[BUF_SIZE];
  1503. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1504. SetText( buf );
  1505. }
  1506. void XMLElement::SetText( float v )
  1507. {
  1508. char buf[BUF_SIZE];
  1509. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1510. SetText( buf );
  1511. }
  1512. void XMLElement::SetText( double v )
  1513. {
  1514. char buf[BUF_SIZE];
  1515. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1516. SetText( buf );
  1517. }
  1518. XMLError XMLElement::QueryIntText( int* ival ) const
  1519. {
  1520. if ( FirstChild() && FirstChild()->ToText() ) {
  1521. const char* t = FirstChild()->Value();
  1522. if ( XMLUtil::ToInt( t, ival ) ) {
  1523. return XML_SUCCESS;
  1524. }
  1525. return XML_CAN_NOT_CONVERT_TEXT;
  1526. }
  1527. return XML_NO_TEXT_NODE;
  1528. }
  1529. XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const
  1530. {
  1531. if ( FirstChild() && FirstChild()->ToText() ) {
  1532. const char* t = FirstChild()->Value();
  1533. if ( XMLUtil::ToUnsigned( t, uval ) ) {
  1534. return XML_SUCCESS;
  1535. }
  1536. return XML_CAN_NOT_CONVERT_TEXT;
  1537. }
  1538. return XML_NO_TEXT_NODE;
  1539. }
  1540. XMLError XMLElement::QueryInt64Text(int64_t* ival) const
  1541. {
  1542. if (FirstChild() && FirstChild()->ToText()) {
  1543. const char* t = FirstChild()->Value();
  1544. if (XMLUtil::ToInt64(t, ival)) {
  1545. return XML_SUCCESS;
  1546. }
  1547. return XML_CAN_NOT_CONVERT_TEXT;
  1548. }
  1549. return XML_NO_TEXT_NODE;
  1550. }
  1551. XMLError XMLElement::QueryUnsigned64Text(uint64_t* uval) const
  1552. {
  1553. if(FirstChild() && FirstChild()->ToText()) {
  1554. const char* t = FirstChild()->Value();
  1555. if(XMLUtil::ToUnsigned64(t, uval)) {
  1556. return XML_SUCCESS;
  1557. }
  1558. return XML_CAN_NOT_CONVERT_TEXT;
  1559. }
  1560. return XML_NO_TEXT_NODE;
  1561. }
  1562. XMLError XMLElement::QueryBoolText( bool* bval ) const
  1563. {
  1564. if ( FirstChild() && FirstChild()->ToText() ) {
  1565. const char* t = FirstChild()->Value();
  1566. if ( XMLUtil::ToBool( t, bval ) ) {
  1567. return XML_SUCCESS;
  1568. }
  1569. return XML_CAN_NOT_CONVERT_TEXT;
  1570. }
  1571. return XML_NO_TEXT_NODE;
  1572. }
  1573. XMLError XMLElement::QueryDoubleText( double* dval ) const
  1574. {
  1575. if ( FirstChild() && FirstChild()->ToText() ) {
  1576. const char* t = FirstChild()->Value();
  1577. if ( XMLUtil::ToDouble( t, dval ) ) {
  1578. return XML_SUCCESS;
  1579. }
  1580. return XML_CAN_NOT_CONVERT_TEXT;
  1581. }
  1582. return XML_NO_TEXT_NODE;
  1583. }
  1584. XMLError XMLElement::QueryFloatText( float* fval ) const
  1585. {
  1586. if ( FirstChild() && FirstChild()->ToText() ) {
  1587. const char* t = FirstChild()->Value();
  1588. if ( XMLUtil::ToFloat( t, fval ) ) {
  1589. return XML_SUCCESS;
  1590. }
  1591. return XML_CAN_NOT_CONVERT_TEXT;
  1592. }
  1593. return XML_NO_TEXT_NODE;
  1594. }
  1595. int XMLElement::IntText(int defaultValue) const
  1596. {
  1597. int i = defaultValue;
  1598. QueryIntText(&i);
  1599. return i;
  1600. }
  1601. unsigned XMLElement::UnsignedText(unsigned defaultValue) const
  1602. {
  1603. unsigned i = defaultValue;
  1604. QueryUnsignedText(&i);
  1605. return i;
  1606. }
  1607. int64_t XMLElement::Int64Text(int64_t defaultValue) const
  1608. {
  1609. int64_t i = defaultValue;
  1610. QueryInt64Text(&i);
  1611. return i;
  1612. }
  1613. uint64_t XMLElement::Unsigned64Text(uint64_t defaultValue) const
  1614. {
  1615. uint64_t i = defaultValue;
  1616. QueryUnsigned64Text(&i);
  1617. return i;
  1618. }
  1619. bool XMLElement::BoolText(bool defaultValue) const
  1620. {
  1621. bool b = defaultValue;
  1622. QueryBoolText(&b);
  1623. return b;
  1624. }
  1625. double XMLElement::DoubleText(double defaultValue) const
  1626. {
  1627. double d = defaultValue;
  1628. QueryDoubleText(&d);
  1629. return d;
  1630. }
  1631. float XMLElement::FloatText(float defaultValue) const
  1632. {
  1633. float f = defaultValue;
  1634. QueryFloatText(&f);
  1635. return f;
  1636. }
  1637. XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name )
  1638. {
  1639. XMLAttribute* last = 0;
  1640. XMLAttribute* attrib = 0;
  1641. for( attrib = _rootAttribute;
  1642. attrib;
  1643. last = attrib, attrib = attrib->_next ) {
  1644. if ( XMLUtil::StringEqual( attrib->Name(), name ) ) {
  1645. break;
  1646. }
  1647. }
  1648. if ( !attrib ) {
  1649. attrib = CreateAttribute();
  1650. TIXMLASSERT( attrib );
  1651. if ( last ) {
  1652. TIXMLASSERT( last->_next == 0 );
  1653. last->_next = attrib;
  1654. }
  1655. else {
  1656. TIXMLASSERT( _rootAttribute == 0 );
  1657. _rootAttribute = attrib;
  1658. }
  1659. attrib->SetName( name );
  1660. }
  1661. return attrib;
  1662. }
  1663. void XMLElement::DeleteAttribute( const char* name )
  1664. {
  1665. XMLAttribute* prev = 0;
  1666. for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) {
  1667. if ( XMLUtil::StringEqual( name, a->Name() ) ) {
  1668. if ( prev ) {
  1669. prev->_next = a->_next;
  1670. }
  1671. else {
  1672. _rootAttribute = a->_next;
  1673. }
  1674. DeleteAttribute( a );
  1675. break;
  1676. }
  1677. prev = a;
  1678. }
  1679. }
  1680. char* XMLElement::ParseAttributes( char* p, int* curLineNumPtr )
  1681. {
  1682. XMLAttribute* prevAttribute = 0;
  1683. // Read the attributes.
  1684. while( p ) {
  1685. p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr );
  1686. if ( !(*p) ) {
  1687. _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name() );
  1688. return 0;
  1689. }
  1690. // attribute.
  1691. if (XMLUtil::IsNameStartChar( static_cast<unsigned char>(*p) ) ) {
  1692. XMLAttribute* attrib = CreateAttribute();
  1693. TIXMLASSERT( attrib );
  1694. attrib->_parseLineNum = _document->_parseCurLineNum;
  1695. const int attrLineNum = attrib->_parseLineNum;
  1696. p = attrib->ParseDeep( p, _document->ProcessEntities(), curLineNumPtr );
  1697. if ( !p || Attribute( attrib->Name() ) ) {
  1698. DeleteAttribute( attrib );
  1699. _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name() );
  1700. return 0;
  1701. }
  1702. // There is a minor bug here: if the attribute in the source xml
  1703. // document is duplicated, it will not be detected and the
  1704. // attribute will be doubly added. However, tracking the 'prevAttribute'
  1705. // avoids re-scanning the attribute list. Preferring performance for
  1706. // now, may reconsider in the future.
  1707. if ( prevAttribute ) {
  1708. TIXMLASSERT( prevAttribute->_next == 0 );
  1709. prevAttribute->_next = attrib;
  1710. }
  1711. else {
  1712. TIXMLASSERT( _rootAttribute == 0 );
  1713. _rootAttribute = attrib;
  1714. }
  1715. prevAttribute = attrib;
  1716. }
  1717. // end of the tag
  1718. else if ( *p == '>' ) {
  1719. ++p;
  1720. break;
  1721. }
  1722. // end of the tag
  1723. else if ( *p == '/' && *(p+1) == '>' ) {
  1724. _closingType = CLOSED;
  1725. return p+2; // done; sealed element.
  1726. }
  1727. else {
  1728. _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0 );
  1729. return 0;
  1730. }
  1731. }
  1732. return p;
  1733. }
  1734. void XMLElement::DeleteAttribute( XMLAttribute* attribute )
  1735. {
  1736. if ( attribute == 0 ) {
  1737. return;
  1738. }
  1739. MemPool* pool = attribute->_memPool;
  1740. attribute->~XMLAttribute();
  1741. pool->Free( attribute );
  1742. }
  1743. XMLAttribute* XMLElement::CreateAttribute()
  1744. {
  1745. TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() );
  1746. XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute();
  1747. TIXMLASSERT( attrib );
  1748. attrib->_memPool = &_document->_attributePool;
  1749. attrib->_memPool->SetTracked();
  1750. return attrib;
  1751. }
  1752. XMLElement* XMLElement::InsertNewChildElement(const char* name)
  1753. {
  1754. XMLElement* node = _document->NewElement(name);
  1755. return InsertEndChild(node) ? node : 0;
  1756. }
  1757. XMLComment* XMLElement::InsertNewComment(const char* comment)
  1758. {
  1759. XMLComment* node = _document->NewComment(comment);
  1760. return InsertEndChild(node) ? node : 0;
  1761. }
  1762. XMLText* XMLElement::InsertNewText(const char* text)
  1763. {
  1764. XMLText* node = _document->NewText(text);
  1765. return InsertEndChild(node) ? node : 0;
  1766. }
  1767. XMLDeclaration* XMLElement::InsertNewDeclaration(const char* text)
  1768. {
  1769. XMLDeclaration* node = _document->NewDeclaration(text);
  1770. return InsertEndChild(node) ? node : 0;
  1771. }
  1772. XMLUnknown* XMLElement::InsertNewUnknown(const char* text)
  1773. {
  1774. XMLUnknown* node = _document->NewUnknown(text);
  1775. return InsertEndChild(node) ? node : 0;
  1776. }
  1777. //
  1778. // <ele></ele>
  1779. // <ele>foo<b>bar</b></ele>
  1780. //
  1781. char* XMLElement::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr )
  1782. {
  1783. // Read the element name.
  1784. p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr );
  1785. // The closing element is the </element> form. It is
  1786. // parsed just like a regular element then deleted from
  1787. // the DOM.
  1788. if ( *p == '/' ) {
  1789. _closingType = CLOSING;
  1790. ++p;
  1791. }
  1792. p = _value.ParseName( p );
  1793. if ( _value.Empty() ) {
  1794. return 0;
  1795. }
  1796. p = ParseAttributes( p, curLineNumPtr );
  1797. if ( !p || !*p || _closingType != OPEN ) {
  1798. return p;
  1799. }
  1800. p = XMLNode::ParseDeep( p, parentEndTag, curLineNumPtr );
  1801. return p;
  1802. }
  1803. XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const
  1804. {
  1805. if ( !doc ) {
  1806. doc = _document;
  1807. }
  1808. XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern?
  1809. for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) {
  1810. element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern?
  1811. }
  1812. return element;
  1813. }
  1814. bool XMLElement::ShallowEqual( const XMLNode* compare ) const
  1815. {
  1816. TIXMLASSERT( compare );
  1817. const XMLElement* other = compare->ToElement();
  1818. if ( other && XMLUtil::StringEqual( other->Name(), Name() )) {
  1819. const XMLAttribute* a=FirstAttribute();
  1820. const XMLAttribute* b=other->FirstAttribute();
  1821. while ( a && b ) {
  1822. if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) {
  1823. return false;
  1824. }
  1825. a = a->Next();
  1826. b = b->Next();
  1827. }
  1828. if ( a || b ) {
  1829. // different count
  1830. return false;
  1831. }
  1832. return true;
  1833. }
  1834. return false;
  1835. }
  1836. bool XMLElement::Accept( XMLVisitor* visitor ) const
  1837. {
  1838. TIXMLASSERT( visitor );
  1839. if ( visitor->VisitEnter( *this, _rootAttribute ) ) {
  1840. for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) {
  1841. if ( !node->Accept( visitor ) ) {
  1842. break;
  1843. }
  1844. }
  1845. }
  1846. return visitor->VisitExit( *this );
  1847. }
  1848. // --------- XMLDocument ----------- //
  1849. // Warning: List must match 'enum XMLError'
  1850. const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = {
  1851. "XML_SUCCESS",
  1852. "XML_NO_ATTRIBUTE",
  1853. "XML_WRONG_ATTRIBUTE_TYPE",
  1854. "XML_ERROR_FILE_NOT_FOUND",
  1855. "XML_ERROR_FILE_COULD_NOT_BE_OPENED",
  1856. "XML_ERROR_FILE_READ_ERROR",
  1857. "XML_ERROR_PARSING_ELEMENT",
  1858. "XML_ERROR_PARSING_ATTRIBUTE",
  1859. "XML_ERROR_PARSING_TEXT",
  1860. "XML_ERROR_PARSING_CDATA",
  1861. "XML_ERROR_PARSING_COMMENT",
  1862. "XML_ERROR_PARSING_DECLARATION",
  1863. "XML_ERROR_PARSING_UNKNOWN",
  1864. "XML_ERROR_EMPTY_DOCUMENT",
  1865. "XML_ERROR_MISMATCHED_ELEMENT",
  1866. "XML_ERROR_PARSING",
  1867. "XML_CAN_NOT_CONVERT_TEXT",
  1868. "XML_NO_TEXT_NODE",
  1869. "XML_ELEMENT_DEPTH_EXCEEDED"
  1870. };
  1871. XMLDocument::XMLDocument( bool processEntities, Whitespace whitespaceMode ) :
  1872. XMLNode( 0 ),
  1873. _writeBOM( false ),
  1874. _processEntities( processEntities ),
  1875. _errorID(XML_SUCCESS),
  1876. _whitespaceMode( whitespaceMode ),
  1877. _errorStr(),
  1878. _errorLineNum( 0 ),
  1879. _charBuffer( 0 ),
  1880. _parseCurLineNum( 0 ),
  1881. _parsingDepth(0),
  1882. _unlinked(),
  1883. _elementPool(),
  1884. _attributePool(),
  1885. _textPool(),
  1886. _commentPool()
  1887. {
  1888. // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+)
  1889. _document = this;
  1890. }
  1891. XMLDocument::~XMLDocument()
  1892. {
  1893. Clear();
  1894. }
  1895. void XMLDocument::MarkInUse(const XMLNode* const node)
  1896. {
  1897. TIXMLASSERT(node);
  1898. TIXMLASSERT(node->_parent == 0);
  1899. for (size_t i = 0; i < _unlinked.Size(); ++i) {
  1900. if (node == _unlinked[i]) {
  1901. _unlinked.SwapRemove(i);
  1902. break;
  1903. }
  1904. }
  1905. }
  1906. void XMLDocument::Clear()
  1907. {
  1908. DeleteChildren();
  1909. while( _unlinked.Size()) {
  1910. DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete.
  1911. }
  1912. #ifdef TINYXML2_DEBUG
  1913. const bool hadError = Error();
  1914. #endif
  1915. ClearError();
  1916. delete [] _charBuffer;
  1917. _charBuffer = 0;
  1918. _parsingDepth = 0;
  1919. #if 0
  1920. _textPool.Trace( "text" );
  1921. _elementPool.Trace( "element" );
  1922. _commentPool.Trace( "comment" );
  1923. _attributePool.Trace( "attribute" );
  1924. #endif
  1925. #ifdef TINYXML2_DEBUG
  1926. if ( !hadError ) {
  1927. TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() );
  1928. TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() );
  1929. TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() );
  1930. TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() );
  1931. }
  1932. #endif
  1933. }
  1934. void XMLDocument::DeepCopy(XMLDocument* target) const
  1935. {
  1936. TIXMLASSERT(target);
  1937. if (target == this) {
  1938. return; // technically success - a no-op.
  1939. }
  1940. target->Clear();
  1941. for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) {
  1942. target->InsertEndChild(node->DeepClone(target));
  1943. }
  1944. }
  1945. XMLElement* XMLDocument::NewElement( const char* name )
  1946. {
  1947. XMLElement* ele = CreateUnlinkedNode<XMLElement>( _elementPool );
  1948. ele->SetName( name );
  1949. return ele;
  1950. }
  1951. XMLComment* XMLDocument::NewComment( const char* str )
  1952. {
  1953. XMLComment* comment = CreateUnlinkedNode<XMLComment>( _commentPool );
  1954. comment->SetValue( str );
  1955. return comment;
  1956. }
  1957. XMLText* XMLDocument::NewText( const char* str )
  1958. {
  1959. XMLText* text = CreateUnlinkedNode<XMLText>( _textPool );
  1960. text->SetValue( str );
  1961. return text;
  1962. }
  1963. XMLDeclaration* XMLDocument::NewDeclaration( const char* str )
  1964. {
  1965. XMLDeclaration* dec = CreateUnlinkedNode<XMLDeclaration>( _commentPool );
  1966. dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" );
  1967. return dec;
  1968. }
  1969. XMLUnknown* XMLDocument::NewUnknown( const char* str )
  1970. {
  1971. XMLUnknown* unk = CreateUnlinkedNode<XMLUnknown>( _commentPool );
  1972. unk->SetValue( str );
  1973. return unk;
  1974. }
  1975. static FILE* callfopen( const char* filepath, const char* mode )
  1976. {
  1977. TIXMLASSERT( filepath );
  1978. TIXMLASSERT( mode );
  1979. #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE)
  1980. FILE* fp = 0;
  1981. const errno_t err = fopen_s( &fp, filepath, mode );
  1982. if ( err ) {
  1983. return 0;
  1984. }
  1985. #else
  1986. FILE* fp = fopen( filepath, mode );
  1987. #endif
  1988. return fp;
  1989. }
  1990. void XMLDocument::DeleteNode( XMLNode* node ) {
  1991. TIXMLASSERT( node );
  1992. TIXMLASSERT(node->_document == this );
  1993. if (node->_parent) {
  1994. node->_parent->DeleteChild( node );
  1995. }
  1996. else {
  1997. // Isn't in the tree.
  1998. // Use the parent delete.
  1999. // Also, we need to mark it tracked: we 'know'
  2000. // it was never used.
  2001. node->_memPool->SetTracked();
  2002. // Call the static XMLNode version:
  2003. XMLNode::DeleteNode(node);
  2004. }
  2005. }
  2006. XMLError XMLDocument::LoadFile( const char* filename )
  2007. {
  2008. if ( !filename ) {
  2009. TIXMLASSERT( false );
  2010. SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=<null>" );
  2011. return _errorID;
  2012. }
  2013. Clear();
  2014. FILE* fp = callfopen( filename, "rb" );
  2015. if ( !fp ) {
  2016. SetError( XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename );
  2017. return _errorID;
  2018. }
  2019. LoadFile( fp );
  2020. fclose( fp );
  2021. return _errorID;
  2022. }
  2023. XMLError XMLDocument::LoadFile( FILE* fp )
  2024. {
  2025. Clear();
  2026. TIXML_FSEEK( fp, 0, SEEK_SET );
  2027. if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) {
  2028. SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
  2029. return _errorID;
  2030. }
  2031. TIXML_FSEEK( fp, 0, SEEK_END );
  2032. unsigned long long filelength;
  2033. {
  2034. const long long fileLengthSigned = TIXML_FTELL( fp );
  2035. TIXML_FSEEK( fp, 0, SEEK_SET );
  2036. if ( fileLengthSigned == -1L ) {
  2037. SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
  2038. return _errorID;
  2039. }
  2040. TIXMLASSERT( fileLengthSigned >= 0 );
  2041. filelength = static_cast<unsigned long long>(fileLengthSigned);
  2042. }
  2043. const size_t maxSizeT = static_cast<size_t>(-1);
  2044. // We'll do the comparison as an unsigned long long, because that's guaranteed to be at
  2045. // least 8 bytes, even on a 32-bit platform.
  2046. if ( filelength >= static_cast<unsigned long long>(maxSizeT) ) {
  2047. // Cannot handle files which won't fit in buffer together with null terminator
  2048. SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
  2049. return _errorID;
  2050. }
  2051. if ( filelength == 0 ) {
  2052. SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
  2053. return _errorID;
  2054. }
  2055. const size_t size = static_cast<size_t>(filelength);
  2056. TIXMLASSERT( _charBuffer == 0 );
  2057. _charBuffer = new char[size+1];
  2058. const size_t read = fread( _charBuffer, 1, size, fp );
  2059. if ( read != size ) {
  2060. SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
  2061. return _errorID;
  2062. }
  2063. _charBuffer[size] = 0;
  2064. Parse();
  2065. return _errorID;
  2066. }
  2067. XMLError XMLDocument::SaveFile( const char* filename, bool compact )
  2068. {
  2069. if ( !filename ) {
  2070. TIXMLASSERT( false );
  2071. SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=<null>" );
  2072. return _errorID;
  2073. }
  2074. FILE* fp = callfopen( filename, "w" );
  2075. if ( !fp ) {
  2076. SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename );
  2077. return _errorID;
  2078. }
  2079. SaveFile(fp, compact);
  2080. fclose( fp );
  2081. return _errorID;
  2082. }
  2083. XMLError XMLDocument::SaveFile( FILE* fp, bool compact )
  2084. {
  2085. // Clear any error from the last save, otherwise it will get reported
  2086. // for *this* call.
  2087. ClearError();
  2088. XMLPrinter stream( fp, compact );
  2089. Print( &stream );
  2090. return _errorID;
  2091. }
  2092. XMLError XMLDocument::Parse( const char* xml, size_t nBytes )
  2093. {
  2094. Clear();
  2095. if ( nBytes == 0 || !xml || !*xml ) {
  2096. SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
  2097. return _errorID;
  2098. }
  2099. if ( nBytes == static_cast<size_t>(-1) ) {
  2100. nBytes = strlen( xml );
  2101. }
  2102. TIXMLASSERT( _charBuffer == 0 );
  2103. _charBuffer = new char[ nBytes+1 ];
  2104. memcpy( _charBuffer, xml, nBytes );
  2105. _charBuffer[nBytes] = 0;
  2106. Parse();
  2107. if ( Error() ) {
  2108. // clean up now essentially dangling memory.
  2109. // and the parse fail can put objects in the
  2110. // pools that are dead and inaccessible.
  2111. DeleteChildren();
  2112. _elementPool.Clear();
  2113. _attributePool.Clear();
  2114. _textPool.Clear();
  2115. _commentPool.Clear();
  2116. }
  2117. return _errorID;
  2118. }
  2119. void XMLDocument::Print( XMLPrinter* streamer ) const
  2120. {
  2121. if ( streamer ) {
  2122. Accept( streamer );
  2123. }
  2124. else {
  2125. XMLPrinter stdoutStreamer( stdout );
  2126. Accept( &stdoutStreamer );
  2127. }
  2128. }
  2129. void XMLDocument::ClearError() {
  2130. _errorID = XML_SUCCESS;
  2131. _errorLineNum = 0;
  2132. _errorStr.Reset();
  2133. }
  2134. void XMLDocument::SetError( XMLError error, int lineNum, const char* format, ... )
  2135. {
  2136. TIXMLASSERT(error >= 0 && error < XML_ERROR_COUNT);
  2137. _errorID = error;
  2138. _errorLineNum = lineNum;
  2139. _errorStr.Reset();
  2140. const size_t BUFFER_SIZE = 1000;
  2141. char* buffer = new char[BUFFER_SIZE];
  2142. TIXMLASSERT(sizeof(error) <= sizeof(int));
  2143. TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d",
  2144. ErrorIDToName(error), static_cast<int>(error), static_cast<unsigned int>(error), lineNum);
  2145. if (format) {
  2146. size_t len = strlen(buffer);
  2147. TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": ");
  2148. len = strlen(buffer);
  2149. va_list va;
  2150. va_start(va, format);
  2151. TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va);
  2152. va_end(va);
  2153. }
  2154. _errorStr.SetStr(buffer);
  2155. delete[] buffer;
  2156. }
  2157. /*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID)
  2158. {
  2159. TIXMLASSERT( errorID >= 0 && errorID < XML_ERROR_COUNT );
  2160. const char* errorName = _errorNames[errorID];
  2161. TIXMLASSERT( errorName && errorName[0] );
  2162. return errorName;
  2163. }
  2164. const char* XMLDocument::ErrorStr() const
  2165. {
  2166. return _errorStr.Empty() ? "" : _errorStr.GetStr();
  2167. }
  2168. void XMLDocument::PrintError() const
  2169. {
  2170. printf("%s\n", ErrorStr());
  2171. }
  2172. const char* XMLDocument::ErrorName() const
  2173. {
  2174. return ErrorIDToName(_errorID);
  2175. }
  2176. void XMLDocument::Parse()
  2177. {
  2178. TIXMLASSERT( NoChildren() ); // Clear() must have been called previously
  2179. TIXMLASSERT( _charBuffer );
  2180. _parseCurLineNum = 1;
  2181. _parseLineNum = 1;
  2182. char* p = _charBuffer;
  2183. p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum );
  2184. p = const_cast<char*>( XMLUtil::ReadBOM( p, &_writeBOM ) );
  2185. if ( !*p ) {
  2186. SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
  2187. return;
  2188. }
  2189. ParseDeep(p, 0, &_parseCurLineNum );
  2190. }
  2191. void XMLDocument::PushDepth()
  2192. {
  2193. _parsingDepth++;
  2194. if (_parsingDepth == TINYXML2_MAX_ELEMENT_DEPTH) {
  2195. SetError(XML_ELEMENT_DEPTH_EXCEEDED, _parseCurLineNum, "Element nesting is too deep." );
  2196. }
  2197. }
  2198. void XMLDocument::PopDepth()
  2199. {
  2200. TIXMLASSERT(_parsingDepth > 0);
  2201. --_parsingDepth;
  2202. }
  2203. XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth, EscapeAposCharsInAttributes aposInAttributes ) :
  2204. _elementJustOpened( false ),
  2205. _stack(),
  2206. _firstElement( true ),
  2207. _fp( file ),
  2208. _depth( depth ),
  2209. _textDepth( -1 ),
  2210. _processEntities( true ),
  2211. _compactMode( compact ),
  2212. _buffer()
  2213. {
  2214. for( int i=0; i<ENTITY_RANGE; ++i ) {
  2215. _entityFlag[i] = false;
  2216. _restrictedEntityFlag[i] = false;
  2217. }
  2218. for( int i=0; i<NUM_ENTITIES; ++i ) {
  2219. const char entityValue = entities[i].value;
  2220. if ((aposInAttributes == ESCAPE_APOS_CHARS_IN_ATTRIBUTES) || (entityValue != SINGLE_QUOTE)) {
  2221. const unsigned char flagIndex = static_cast<unsigned char>(entityValue);
  2222. TIXMLASSERT( flagIndex < ENTITY_RANGE );
  2223. _entityFlag[flagIndex] = true;
  2224. }
  2225. }
  2226. _restrictedEntityFlag[static_cast<unsigned char>('&')] = true;
  2227. _restrictedEntityFlag[static_cast<unsigned char>('<')] = true;
  2228. _restrictedEntityFlag[static_cast<unsigned char>('>')] = true; // not required, but consistency is nice
  2229. _buffer.Push( 0 );
  2230. }
  2231. void XMLPrinter::Print( const char* format, ... )
  2232. {
  2233. va_list va;
  2234. va_start( va, format );
  2235. if ( _fp ) {
  2236. vfprintf( _fp, format, va );
  2237. }
  2238. else {
  2239. const int len = TIXML_VSCPRINTF( format, va );
  2240. // Close out and re-start the va-args
  2241. va_end( va );
  2242. TIXMLASSERT( len >= 0 );
  2243. va_start( va, format );
  2244. TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 );
  2245. char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator.
  2246. TIXML_VSNPRINTF( p, len+1, format, va );
  2247. }
  2248. va_end( va );
  2249. }
  2250. void XMLPrinter::Write( const char* data, size_t size )
  2251. {
  2252. if ( _fp ) {
  2253. fwrite ( data , sizeof(char), size, _fp);
  2254. }
  2255. else {
  2256. char* p = _buffer.PushArr( static_cast<int>(size) ) - 1; // back up over the null terminator.
  2257. memcpy( p, data, size );
  2258. p[size] = 0;
  2259. }
  2260. }
  2261. void XMLPrinter::Putc( char ch )
  2262. {
  2263. if ( _fp ) {
  2264. fputc ( ch, _fp);
  2265. }
  2266. else {
  2267. char* p = _buffer.PushArr( sizeof(char) ) - 1; // back up over the null terminator.
  2268. p[0] = ch;
  2269. p[1] = 0;
  2270. }
  2271. }
  2272. void XMLPrinter::PrintSpace( int depth )
  2273. {
  2274. for( int i=0; i<depth; ++i ) {
  2275. Write( " " );
  2276. }
  2277. }
  2278. void XMLPrinter::PrintString( const char* p, bool restricted )
  2279. {
  2280. // Look for runs of bytes between entities to print.
  2281. const char* q = p;
  2282. if ( _processEntities ) {
  2283. const bool* flag = restricted ? _restrictedEntityFlag : _entityFlag;
  2284. while ( *q ) {
  2285. TIXMLASSERT( p <= q );
  2286. // Remember, char is sometimes signed. (How many times has that bitten me?)
  2287. if ( *q > 0 && *q < ENTITY_RANGE ) {
  2288. // Check for entities. If one is found, flush
  2289. // the stream up until the entity, write the
  2290. // entity, and keep looking.
  2291. if ( flag[static_cast<unsigned char>(*q)] ) {
  2292. while ( p < q ) {
  2293. const size_t delta = q - p;
  2294. const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast<int>(delta);
  2295. Write( p, toPrint );
  2296. p += toPrint;
  2297. }
  2298. bool entityPatternPrinted = false;
  2299. for( int i=0; i<NUM_ENTITIES; ++i ) {
  2300. if ( entities[i].value == *q ) {
  2301. Putc( '&' );
  2302. Write( entities[i].pattern, entities[i].length );
  2303. Putc( ';' );
  2304. entityPatternPrinted = true;
  2305. break;
  2306. }
  2307. }
  2308. if ( !entityPatternPrinted ) {
  2309. // TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable in release
  2310. TIXMLASSERT( false );
  2311. }
  2312. ++p;
  2313. }
  2314. }
  2315. ++q;
  2316. TIXMLASSERT( p <= q );
  2317. }
  2318. // Flush the remaining string. This will be the entire
  2319. // string if an entity wasn't found.
  2320. if ( p < q ) {
  2321. const size_t delta = q - p;
  2322. const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast<int>(delta);
  2323. Write( p, toPrint );
  2324. }
  2325. }
  2326. else {
  2327. Write( p );
  2328. }
  2329. }
  2330. void XMLPrinter::PushHeader( bool writeBOM, bool writeDec )
  2331. {
  2332. if ( writeBOM ) {
  2333. static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 };
  2334. Write( reinterpret_cast< const char* >( bom ) );
  2335. }
  2336. if ( writeDec ) {
  2337. PushDeclaration( "xml version=\"1.0\"" );
  2338. }
  2339. }
  2340. void XMLPrinter::PrepareForNewNode( bool compactMode )
  2341. {
  2342. SealElementIfJustOpened();
  2343. if ( compactMode ) {
  2344. return;
  2345. }
  2346. if ( _firstElement ) {
  2347. PrintSpace (_depth);
  2348. } else if ( _textDepth < 0) {
  2349. Putc( '\n' );
  2350. PrintSpace( _depth );
  2351. }
  2352. _firstElement = false;
  2353. }
  2354. void XMLPrinter::OpenElement( const char* name, bool compactMode )
  2355. {
  2356. PrepareForNewNode( compactMode );
  2357. _stack.Push( name );
  2358. Write ( "<" );
  2359. Write ( name );
  2360. _elementJustOpened = true;
  2361. ++_depth;
  2362. }
  2363. void XMLPrinter::PushAttribute( const char* name, const char* value )
  2364. {
  2365. TIXMLASSERT( _elementJustOpened );
  2366. Putc ( ' ' );
  2367. Write( name );
  2368. Write( "=\"" );
  2369. PrintString( value, false );
  2370. Putc ( '\"' );
  2371. }
  2372. void XMLPrinter::PushAttribute( const char* name, int v )
  2373. {
  2374. char buf[BUF_SIZE];
  2375. XMLUtil::ToStr( v, buf, BUF_SIZE );
  2376. PushAttribute( name, buf );
  2377. }
  2378. void XMLPrinter::PushAttribute( const char* name, unsigned v )
  2379. {
  2380. char buf[BUF_SIZE];
  2381. XMLUtil::ToStr( v, buf, BUF_SIZE );
  2382. PushAttribute( name, buf );
  2383. }
  2384. void XMLPrinter::PushAttribute(const char* name, int64_t v)
  2385. {
  2386. char buf[BUF_SIZE];
  2387. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2388. PushAttribute(name, buf);
  2389. }
  2390. void XMLPrinter::PushAttribute(const char* name, uint64_t v)
  2391. {
  2392. char buf[BUF_SIZE];
  2393. XMLUtil::ToStr(v, buf, BUF_SIZE);
  2394. PushAttribute(name, buf);
  2395. }
  2396. void XMLPrinter::PushAttribute( const char* name, bool v )
  2397. {
  2398. char buf[BUF_SIZE];
  2399. XMLUtil::ToStr( v, buf, BUF_SIZE );
  2400. PushAttribute( name, buf );
  2401. }
  2402. void XMLPrinter::PushAttribute( const char* name, double v )
  2403. {
  2404. char buf[BUF_SIZE];
  2405. XMLUtil::ToStr( v, buf, BUF_SIZE );
  2406. PushAttribute( name, buf );
  2407. }
  2408. void XMLPrinter::CloseElement( bool compactMode )
  2409. {
  2410. --_depth;
  2411. const char* name = _stack.Pop();
  2412. if ( _elementJustOpened ) {
  2413. Write( "/>" );
  2414. }
  2415. else {
  2416. if ( _textDepth < 0 && !compactMode) {
  2417. Putc( '\n' );
  2418. PrintSpace( _depth );
  2419. }
  2420. Write ( "</" );
  2421. Write ( name );
  2422. Write ( ">" );
  2423. }
  2424. if ( _textDepth == _depth ) {
  2425. _textDepth = -1;
  2426. }
  2427. if ( _depth == 0 && !compactMode) {
  2428. Putc( '\n' );
  2429. }
  2430. _elementJustOpened = false;
  2431. }
  2432. void XMLPrinter::SealElementIfJustOpened()
  2433. {
  2434. if ( !_elementJustOpened ) {
  2435. return;
  2436. }
  2437. _elementJustOpened = false;
  2438. Putc( '>' );
  2439. }
  2440. void XMLPrinter::PushText( const char* text, bool cdata )
  2441. {
  2442. _textDepth = _depth-1;
  2443. SealElementIfJustOpened();
  2444. if ( cdata ) {
  2445. Write( "<![CDATA[" );
  2446. Write( text );
  2447. Write( "]]>" );
  2448. }
  2449. else {
  2450. PrintString( text, true );
  2451. }
  2452. }
  2453. void XMLPrinter::PushText( int64_t value )
  2454. {
  2455. char buf[BUF_SIZE];
  2456. XMLUtil::ToStr( value, buf, BUF_SIZE );
  2457. PushText( buf, false );
  2458. }
  2459. void XMLPrinter::PushText( uint64_t value )
  2460. {
  2461. char buf[BUF_SIZE];
  2462. XMLUtil::ToStr(value, buf, BUF_SIZE);
  2463. PushText(buf, false);
  2464. }
  2465. void XMLPrinter::PushText( int value )
  2466. {
  2467. char buf[BUF_SIZE];
  2468. XMLUtil::ToStr( value, buf, BUF_SIZE );
  2469. PushText( buf, false );
  2470. }
  2471. void XMLPrinter::PushText( unsigned value )
  2472. {
  2473. char buf[BUF_SIZE];
  2474. XMLUtil::ToStr( value, buf, BUF_SIZE );
  2475. PushText( buf, false );
  2476. }
  2477. void XMLPrinter::PushText( bool value )
  2478. {
  2479. char buf[BUF_SIZE];
  2480. XMLUtil::ToStr( value, buf, BUF_SIZE );
  2481. PushText( buf, false );
  2482. }
  2483. void XMLPrinter::PushText( float value )
  2484. {
  2485. char buf[BUF_SIZE];
  2486. XMLUtil::ToStr( value, buf, BUF_SIZE );
  2487. PushText( buf, false );
  2488. }
  2489. void XMLPrinter::PushText( double value )
  2490. {
  2491. char buf[BUF_SIZE];
  2492. XMLUtil::ToStr( value, buf, BUF_SIZE );
  2493. PushText( buf, false );
  2494. }
  2495. void XMLPrinter::PushComment( const char* comment )
  2496. {
  2497. PrepareForNewNode( _compactMode );
  2498. Write( "<!--" );
  2499. Write( comment );
  2500. Write( "-->" );
  2501. }
  2502. void XMLPrinter::PushDeclaration( const char* value )
  2503. {
  2504. PrepareForNewNode( _compactMode );
  2505. Write( "<?" );
  2506. Write( value );
  2507. Write( "?>" );
  2508. }
  2509. void XMLPrinter::PushUnknown( const char* value )
  2510. {
  2511. PrepareForNewNode( _compactMode );
  2512. Write( "<!" );
  2513. Write( value );
  2514. Putc( '>' );
  2515. }
  2516. bool XMLPrinter::VisitEnter( const XMLDocument& doc )
  2517. {
  2518. _processEntities = doc.ProcessEntities();
  2519. if ( doc.HasBOM() ) {
  2520. PushHeader( true, false );
  2521. }
  2522. return true;
  2523. }
  2524. bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute )
  2525. {
  2526. const XMLElement* parentElem = 0;
  2527. if ( element.Parent() ) {
  2528. parentElem = element.Parent()->ToElement();
  2529. }
  2530. const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode;
  2531. OpenElement( element.Name(), compactMode );
  2532. while ( attribute ) {
  2533. PushAttribute( attribute->Name(), attribute->Value() );
  2534. attribute = attribute->Next();
  2535. }
  2536. return true;
  2537. }
  2538. bool XMLPrinter::VisitExit( const XMLElement& element )
  2539. {
  2540. CloseElement( CompactMode(element) );
  2541. return true;
  2542. }
  2543. bool XMLPrinter::Visit( const XMLText& text )
  2544. {
  2545. PushText( text.Value(), text.CData() );
  2546. return true;
  2547. }
  2548. bool XMLPrinter::Visit( const XMLComment& comment )
  2549. {
  2550. PushComment( comment.Value() );
  2551. return true;
  2552. }
  2553. bool XMLPrinter::Visit( const XMLDeclaration& declaration )
  2554. {
  2555. PushDeclaration( declaration.Value() );
  2556. return true;
  2557. }
  2558. bool XMLPrinter::Visit( const XMLUnknown& unknown )
  2559. {
  2560. PushUnknown( unknown.Value() );
  2561. return true;
  2562. }
  2563. } // namespace tinyxml2