tinyxml2.cpp 73 KB

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