tinyxml2.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467
  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. 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. 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. static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF
  93. static const char LF = LINE_FEED;
  94. static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out
  95. static const char CR = CARRIAGE_RETURN;
  96. static const char SINGLE_QUOTE = '\'';
  97. static const char DOUBLE_QUOTE = '\"';
  98. // Bunch of unicode info at:
  99. // http://www.unicode.org/faq/utf_bom.html
  100. // ef bb bf (Microsoft "lead bytes") - designates UTF-8
  101. static const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
  102. static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
  103. static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
  104. namespace tinyxml2
  105. {
  106. struct Entity {
  107. const char* pattern;
  108. int length;
  109. char value;
  110. };
  111. static const int NUM_ENTITIES = 5;
  112. static const Entity entities[NUM_ENTITIES] = {
  113. { "quot", 4, DOUBLE_QUOTE },
  114. { "amp", 3, '&' },
  115. { "apos", 4, SINGLE_QUOTE },
  116. { "lt", 2, '<' },
  117. { "gt", 2, '>' }
  118. };
  119. StrPair::~StrPair()
  120. {
  121. Reset();
  122. }
  123. void StrPair::TransferTo( StrPair* other )
  124. {
  125. if ( this == other ) {
  126. return;
  127. }
  128. // This in effect implements the assignment operator by "moving"
  129. // ownership (as in auto_ptr).
  130. TIXMLASSERT( other->_flags == 0 );
  131. TIXMLASSERT( other->_start == 0 );
  132. TIXMLASSERT( other->_end == 0 );
  133. other->Reset();
  134. other->_flags = _flags;
  135. other->_start = _start;
  136. other->_end = _end;
  137. _flags = 0;
  138. _start = 0;
  139. _end = 0;
  140. }
  141. void StrPair::Reset()
  142. {
  143. if ( _flags & NEEDS_DELETE ) {
  144. delete [] _start;
  145. }
  146. _flags = 0;
  147. _start = 0;
  148. _end = 0;
  149. }
  150. void StrPair::SetStr( const char* str, int flags )
  151. {
  152. TIXMLASSERT( str );
  153. Reset();
  154. size_t len = strlen( str );
  155. TIXMLASSERT( _start == 0 );
  156. _start = new char[ len+1 ];
  157. memcpy( _start, str, len+1 );
  158. _end = _start + len;
  159. _flags = flags | NEEDS_DELETE;
  160. }
  161. char* StrPair::ParseText( char* p, const char* endTag, int strFlags )
  162. {
  163. TIXMLASSERT( endTag && *endTag );
  164. char* start = p;
  165. char endChar = *endTag;
  166. size_t length = strlen( endTag );
  167. // Inner loop of text parsing.
  168. while ( *p ) {
  169. if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) {
  170. Set( start, p, strFlags );
  171. return p + length;
  172. }
  173. ++p;
  174. }
  175. return 0;
  176. }
  177. char* StrPair::ParseName( char* p )
  178. {
  179. if ( !p || !(*p) ) {
  180. return 0;
  181. }
  182. if ( !XMLUtil::IsNameStartChar( *p ) ) {
  183. return 0;
  184. }
  185. char* const start = p;
  186. ++p;
  187. while ( *p && XMLUtil::IsNameChar( *p ) ) {
  188. ++p;
  189. }
  190. Set( start, p, 0 );
  191. return p;
  192. }
  193. void StrPair::CollapseWhitespace()
  194. {
  195. // Adjusting _start would cause undefined behavior on delete[]
  196. TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 );
  197. // Trim leading space.
  198. _start = XMLUtil::SkipWhiteSpace( _start );
  199. if ( *_start ) {
  200. char* p = _start; // the read pointer
  201. char* q = _start; // the write pointer
  202. while( *p ) {
  203. if ( XMLUtil::IsWhiteSpace( *p )) {
  204. p = XMLUtil::SkipWhiteSpace( p );
  205. if ( *p == 0 ) {
  206. break; // don't write to q; this trims the trailing space.
  207. }
  208. *q = ' ';
  209. ++q;
  210. }
  211. *q = *p;
  212. ++q;
  213. ++p;
  214. }
  215. *q = 0;
  216. }
  217. }
  218. const char* StrPair::GetStr()
  219. {
  220. TIXMLASSERT( _start );
  221. TIXMLASSERT( _end );
  222. if ( _flags & NEEDS_FLUSH ) {
  223. *_end = 0;
  224. _flags ^= NEEDS_FLUSH;
  225. if ( _flags ) {
  226. char* p = _start; // the read pointer
  227. char* q = _start; // the write pointer
  228. while( p < _end ) {
  229. if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) {
  230. // CR-LF pair becomes LF
  231. // CR alone becomes LF
  232. // LF-CR becomes LF
  233. if ( *(p+1) == LF ) {
  234. p += 2;
  235. }
  236. else {
  237. ++p;
  238. }
  239. *q++ = LF;
  240. }
  241. else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) {
  242. if ( *(p+1) == CR ) {
  243. p += 2;
  244. }
  245. else {
  246. ++p;
  247. }
  248. *q++ = LF;
  249. }
  250. else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) {
  251. // Entities handled by tinyXML2:
  252. // - special entities in the entity table [in/out]
  253. // - numeric character reference [in]
  254. // &#20013; or &#x4e2d;
  255. if ( *(p+1) == '#' ) {
  256. const int buflen = 10;
  257. char buf[buflen] = { 0 };
  258. int len = 0;
  259. char* adjusted = const_cast<char*>( XMLUtil::GetCharacterRef( p, buf, &len ) );
  260. if ( adjusted == 0 ) {
  261. *q = *p;
  262. ++p;
  263. ++q;
  264. }
  265. else {
  266. TIXMLASSERT( 0 <= len && len <= buflen );
  267. TIXMLASSERT( q + len <= adjusted );
  268. p = adjusted;
  269. memcpy( q, buf, len );
  270. q += len;
  271. }
  272. }
  273. else {
  274. bool entityFound = false;
  275. for( int i = 0; i < NUM_ENTITIES; ++i ) {
  276. const Entity& entity = entities[i];
  277. if ( strncmp( p + 1, entity.pattern, entity.length ) == 0
  278. && *( p + entity.length + 1 ) == ';' ) {
  279. // Found an entity - convert.
  280. *q = entity.value;
  281. ++q;
  282. p += entity.length + 2;
  283. entityFound = true;
  284. break;
  285. }
  286. }
  287. if ( !entityFound ) {
  288. // fixme: treat as error?
  289. ++p;
  290. ++q;
  291. }
  292. }
  293. }
  294. else {
  295. *q = *p;
  296. ++p;
  297. ++q;
  298. }
  299. }
  300. *q = 0;
  301. }
  302. // The loop below has plenty going on, and this
  303. // is a less useful mode. Break it out.
  304. if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) {
  305. CollapseWhitespace();
  306. }
  307. _flags = (_flags & NEEDS_DELETE);
  308. }
  309. TIXMLASSERT( _start );
  310. return _start;
  311. }
  312. // --------- XMLUtil ----------- //
  313. const char* XMLUtil::ReadBOM( const char* p, bool* bom )
  314. {
  315. TIXMLASSERT( p );
  316. TIXMLASSERT( bom );
  317. *bom = false;
  318. const unsigned char* pu = reinterpret_cast<const unsigned char*>(p);
  319. // Check for BOM:
  320. if ( *(pu+0) == TIXML_UTF_LEAD_0
  321. && *(pu+1) == TIXML_UTF_LEAD_1
  322. && *(pu+2) == TIXML_UTF_LEAD_2 ) {
  323. *bom = true;
  324. p += 3;
  325. }
  326. TIXMLASSERT( p );
  327. return p;
  328. }
  329. void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length )
  330. {
  331. const unsigned long BYTE_MASK = 0xBF;
  332. const unsigned long BYTE_MARK = 0x80;
  333. const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  334. if (input < 0x80) {
  335. *length = 1;
  336. }
  337. else if ( input < 0x800 ) {
  338. *length = 2;
  339. }
  340. else if ( input < 0x10000 ) {
  341. *length = 3;
  342. }
  343. else if ( input < 0x200000 ) {
  344. *length = 4;
  345. }
  346. else {
  347. *length = 0; // This code won't convert this correctly anyway.
  348. return;
  349. }
  350. output += *length;
  351. // Scary scary fall throughs.
  352. switch (*length) {
  353. case 4:
  354. --output;
  355. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  356. input >>= 6;
  357. case 3:
  358. --output;
  359. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  360. input >>= 6;
  361. case 2:
  362. --output;
  363. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  364. input >>= 6;
  365. case 1:
  366. --output;
  367. *output = (char)(input | FIRST_BYTE_MARK[*length]);
  368. break;
  369. default:
  370. TIXMLASSERT( false );
  371. }
  372. }
  373. const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length )
  374. {
  375. // Presume an entity, and pull it out.
  376. *length = 0;
  377. if ( *(p+1) == '#' && *(p+2) ) {
  378. unsigned long ucs = 0;
  379. TIXMLASSERT( sizeof( ucs ) >= 4 );
  380. ptrdiff_t delta = 0;
  381. unsigned mult = 1;
  382. static const char SEMICOLON = ';';
  383. if ( *(p+2) == 'x' ) {
  384. // Hexadecimal.
  385. const char* q = p+3;
  386. if ( !(*q) ) {
  387. return 0;
  388. }
  389. q = strchr( q, SEMICOLON );
  390. if ( !q ) {
  391. return 0;
  392. }
  393. TIXMLASSERT( *q == SEMICOLON );
  394. delta = q-p;
  395. --q;
  396. while ( *q != 'x' ) {
  397. unsigned int digit = 0;
  398. if ( *q >= '0' && *q <= '9' ) {
  399. digit = *q - '0';
  400. }
  401. else if ( *q >= 'a' && *q <= 'f' ) {
  402. digit = *q - 'a' + 10;
  403. }
  404. else if ( *q >= 'A' && *q <= 'F' ) {
  405. digit = *q - 'A' + 10;
  406. }
  407. else {
  408. return 0;
  409. }
  410. TIXMLASSERT( digit < 16 );
  411. TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit );
  412. const unsigned int digitScaled = mult * digit;
  413. TIXMLASSERT( ucs <= ULONG_MAX - digitScaled );
  414. ucs += digitScaled;
  415. TIXMLASSERT( mult <= UINT_MAX / 16 );
  416. mult *= 16;
  417. --q;
  418. }
  419. }
  420. else {
  421. // Decimal.
  422. const char* q = p+2;
  423. if ( !(*q) ) {
  424. return 0;
  425. }
  426. q = strchr( q, SEMICOLON );
  427. if ( !q ) {
  428. return 0;
  429. }
  430. TIXMLASSERT( *q == SEMICOLON );
  431. delta = q-p;
  432. --q;
  433. while ( *q != '#' ) {
  434. if ( *q >= '0' && *q <= '9' ) {
  435. const unsigned int digit = *q - '0';
  436. TIXMLASSERT( digit < 10 );
  437. TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit );
  438. const unsigned int digitScaled = mult * digit;
  439. TIXMLASSERT( ucs <= ULONG_MAX - digitScaled );
  440. ucs += digitScaled;
  441. }
  442. else {
  443. return 0;
  444. }
  445. TIXMLASSERT( mult <= UINT_MAX / 10 );
  446. mult *= 10;
  447. --q;
  448. }
  449. }
  450. // convert the UCS to UTF-8
  451. ConvertUTF32ToUTF8( ucs, value, length );
  452. return p + delta + 1;
  453. }
  454. return p+1;
  455. }
  456. void XMLUtil::ToStr( int v, char* buffer, int bufferSize )
  457. {
  458. TIXML_SNPRINTF( buffer, bufferSize, "%d", v );
  459. }
  460. void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize )
  461. {
  462. TIXML_SNPRINTF( buffer, bufferSize, "%u", v );
  463. }
  464. void XMLUtil::ToStr( bool v, char* buffer, int bufferSize )
  465. {
  466. TIXML_SNPRINTF( buffer, bufferSize, "%d", v ? 1 : 0 );
  467. }
  468. /*
  469. ToStr() of a number is a very tricky topic.
  470. https://github.com/leethomason/tinyxml2/issues/106
  471. */
  472. void XMLUtil::ToStr( float v, char* buffer, int bufferSize )
  473. {
  474. TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v );
  475. }
  476. void XMLUtil::ToStr( double v, char* buffer, int bufferSize )
  477. {
  478. TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v );
  479. }
  480. bool XMLUtil::ToInt( const char* str, int* value )
  481. {
  482. if ( TIXML_SSCANF( str, "%d", value ) == 1 ) {
  483. return true;
  484. }
  485. return false;
  486. }
  487. bool XMLUtil::ToUnsigned( const char* str, unsigned *value )
  488. {
  489. if ( TIXML_SSCANF( str, "%u", value ) == 1 ) {
  490. return true;
  491. }
  492. return false;
  493. }
  494. bool XMLUtil::ToBool( const char* str, bool* value )
  495. {
  496. int ival = 0;
  497. if ( ToInt( str, &ival )) {
  498. *value = (ival==0) ? false : true;
  499. return true;
  500. }
  501. if ( StringEqual( str, "true" ) ) {
  502. *value = true;
  503. return true;
  504. }
  505. else if ( StringEqual( str, "false" ) ) {
  506. *value = false;
  507. return true;
  508. }
  509. return false;
  510. }
  511. bool XMLUtil::ToFloat( const char* str, float* value )
  512. {
  513. if ( TIXML_SSCANF( str, "%f", value ) == 1 ) {
  514. return true;
  515. }
  516. return false;
  517. }
  518. bool XMLUtil::ToDouble( const char* str, double* value )
  519. {
  520. if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) {
  521. return true;
  522. }
  523. return false;
  524. }
  525. char* XMLDocument::Identify( char* p, XMLNode** node )
  526. {
  527. TIXMLASSERT( node );
  528. TIXMLASSERT( p );
  529. char* const start = p;
  530. p = XMLUtil::SkipWhiteSpace( p );
  531. if( !*p ) {
  532. *node = 0;
  533. TIXMLASSERT( p );
  534. return p;
  535. }
  536. // These strings define the matching patterns:
  537. static const char* xmlHeader = { "<?" };
  538. static const char* commentHeader = { "<!--" };
  539. static const char* cdataHeader = { "<![CDATA[" };
  540. static const char* dtdHeader = { "<!" };
  541. static const char* elementHeader = { "<" }; // and a header for everything else; check last.
  542. static const int xmlHeaderLen = 2;
  543. static const int commentHeaderLen = 4;
  544. static const int cdataHeaderLen = 9;
  545. static const int dtdHeaderLen = 2;
  546. static const int elementHeaderLen = 1;
  547. TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLUnknown ) ); // use same memory pool
  548. TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLDeclaration ) ); // use same memory pool
  549. XMLNode* returnNode = 0;
  550. if ( XMLUtil::StringEqual( p, xmlHeader, xmlHeaderLen ) ) {
  551. TIXMLASSERT( sizeof( XMLDeclaration ) == _commentPool.ItemSize() );
  552. returnNode = new (_commentPool.Alloc()) XMLDeclaration( this );
  553. returnNode->_memPool = &_commentPool;
  554. p += xmlHeaderLen;
  555. }
  556. else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) {
  557. TIXMLASSERT( sizeof( XMLComment ) == _commentPool.ItemSize() );
  558. returnNode = new (_commentPool.Alloc()) XMLComment( this );
  559. returnNode->_memPool = &_commentPool;
  560. p += commentHeaderLen;
  561. }
  562. else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) {
  563. TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() );
  564. XMLText* text = new (_textPool.Alloc()) XMLText( this );
  565. returnNode = text;
  566. returnNode->_memPool = &_textPool;
  567. p += cdataHeaderLen;
  568. text->SetCData( true );
  569. }
  570. else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) {
  571. TIXMLASSERT( sizeof( XMLUnknown ) == _commentPool.ItemSize() );
  572. returnNode = new (_commentPool.Alloc()) XMLUnknown( this );
  573. returnNode->_memPool = &_commentPool;
  574. p += dtdHeaderLen;
  575. }
  576. else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) {
  577. TIXMLASSERT( sizeof( XMLElement ) == _elementPool.ItemSize() );
  578. returnNode = new (_elementPool.Alloc()) XMLElement( this );
  579. returnNode->_memPool = &_elementPool;
  580. p += elementHeaderLen;
  581. }
  582. else {
  583. TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() );
  584. returnNode = new (_textPool.Alloc()) XMLText( this );
  585. returnNode->_memPool = &_textPool;
  586. p = start; // Back it up, all the text counts.
  587. }
  588. TIXMLASSERT( returnNode );
  589. TIXMLASSERT( p );
  590. *node = returnNode;
  591. return p;
  592. }
  593. bool XMLDocument::Accept( XMLVisitor* visitor ) const
  594. {
  595. TIXMLASSERT( visitor );
  596. if ( visitor->VisitEnter( *this ) ) {
  597. for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) {
  598. if ( !node->Accept( visitor ) ) {
  599. break;
  600. }
  601. }
  602. }
  603. return visitor->VisitExit( *this );
  604. }
  605. // --------- XMLNode ----------- //
  606. XMLNode::XMLNode( XMLDocument* doc ) :
  607. _document( doc ),
  608. _parent( 0 ),
  609. _firstChild( 0 ), _lastChild( 0 ),
  610. _prev( 0 ), _next( 0 ),
  611. _memPool( 0 )
  612. {
  613. }
  614. XMLNode::~XMLNode()
  615. {
  616. DeleteChildren();
  617. if ( _parent ) {
  618. _parent->Unlink( this );
  619. }
  620. }
  621. const char* XMLNode::Value() const
  622. {
  623. // Catch an edge case: XMLDocuments don't have a a Value. Carefully return nullptr.
  624. if ( this->ToDocument() )
  625. return 0;
  626. return _value.GetStr();
  627. }
  628. void XMLNode::SetValue( const char* str, bool staticMem )
  629. {
  630. if ( staticMem ) {
  631. _value.SetInternedStr( str );
  632. }
  633. else {
  634. _value.SetStr( str );
  635. }
  636. }
  637. void XMLNode::DeleteChildren()
  638. {
  639. while( _firstChild ) {
  640. TIXMLASSERT( _lastChild );
  641. TIXMLASSERT( _firstChild->_document == _document );
  642. XMLNode* node = _firstChild;
  643. Unlink( node );
  644. DeleteNode( node );
  645. }
  646. _firstChild = _lastChild = 0;
  647. }
  648. void XMLNode::Unlink( XMLNode* child )
  649. {
  650. TIXMLASSERT( child );
  651. TIXMLASSERT( child->_document == _document );
  652. TIXMLASSERT( child->_parent == this );
  653. if ( child == _firstChild ) {
  654. _firstChild = _firstChild->_next;
  655. }
  656. if ( child == _lastChild ) {
  657. _lastChild = _lastChild->_prev;
  658. }
  659. if ( child->_prev ) {
  660. child->_prev->_next = child->_next;
  661. }
  662. if ( child->_next ) {
  663. child->_next->_prev = child->_prev;
  664. }
  665. child->_parent = 0;
  666. }
  667. void XMLNode::DeleteChild( XMLNode* node )
  668. {
  669. TIXMLASSERT( node );
  670. TIXMLASSERT( node->_document == _document );
  671. TIXMLASSERT( node->_parent == this );
  672. Unlink( node );
  673. DeleteNode( node );
  674. }
  675. XMLNode* XMLNode::InsertEndChild( XMLNode* addThis )
  676. {
  677. TIXMLASSERT( addThis );
  678. if ( addThis->_document != _document ) {
  679. TIXMLASSERT( false );
  680. return 0;
  681. }
  682. InsertChildPreamble( addThis );
  683. if ( _lastChild ) {
  684. TIXMLASSERT( _firstChild );
  685. TIXMLASSERT( _lastChild->_next == 0 );
  686. _lastChild->_next = addThis;
  687. addThis->_prev = _lastChild;
  688. _lastChild = addThis;
  689. addThis->_next = 0;
  690. }
  691. else {
  692. TIXMLASSERT( _firstChild == 0 );
  693. _firstChild = _lastChild = addThis;
  694. addThis->_prev = 0;
  695. addThis->_next = 0;
  696. }
  697. addThis->_parent = this;
  698. return addThis;
  699. }
  700. XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis )
  701. {
  702. TIXMLASSERT( addThis );
  703. if ( addThis->_document != _document ) {
  704. TIXMLASSERT( false );
  705. return 0;
  706. }
  707. InsertChildPreamble( addThis );
  708. if ( _firstChild ) {
  709. TIXMLASSERT( _lastChild );
  710. TIXMLASSERT( _firstChild->_prev == 0 );
  711. _firstChild->_prev = addThis;
  712. addThis->_next = _firstChild;
  713. _firstChild = addThis;
  714. addThis->_prev = 0;
  715. }
  716. else {
  717. TIXMLASSERT( _lastChild == 0 );
  718. _firstChild = _lastChild = addThis;
  719. addThis->_prev = 0;
  720. addThis->_next = 0;
  721. }
  722. addThis->_parent = this;
  723. return addThis;
  724. }
  725. XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis )
  726. {
  727. TIXMLASSERT( addThis );
  728. if ( addThis->_document != _document ) {
  729. TIXMLASSERT( false );
  730. return 0;
  731. }
  732. TIXMLASSERT( afterThis );
  733. if ( afterThis->_parent != this ) {
  734. TIXMLASSERT( false );
  735. return 0;
  736. }
  737. if ( afterThis->_next == 0 ) {
  738. // The last node or the only node.
  739. return InsertEndChild( addThis );
  740. }
  741. InsertChildPreamble( addThis );
  742. addThis->_prev = afterThis;
  743. addThis->_next = afterThis->_next;
  744. afterThis->_next->_prev = addThis;
  745. afterThis->_next = addThis;
  746. addThis->_parent = this;
  747. return addThis;
  748. }
  749. const XMLElement* XMLNode::FirstChildElement( const char* name ) const
  750. {
  751. for( const XMLNode* node = _firstChild; node; node = node->_next ) {
  752. const XMLElement* element = node->ToElement();
  753. if ( element ) {
  754. if ( !name || XMLUtil::StringEqual( element->Name(), name ) ) {
  755. return element;
  756. }
  757. }
  758. }
  759. return 0;
  760. }
  761. const XMLElement* XMLNode::LastChildElement( const char* name ) const
  762. {
  763. for( const XMLNode* node = _lastChild; node; node = node->_prev ) {
  764. const XMLElement* element = node->ToElement();
  765. if ( element ) {
  766. if ( !name || XMLUtil::StringEqual( element->Name(), name ) ) {
  767. return element;
  768. }
  769. }
  770. }
  771. return 0;
  772. }
  773. const XMLElement* XMLNode::NextSiblingElement( const char* name ) const
  774. {
  775. for( const XMLNode* node = _next; node; node = node->_next ) {
  776. const XMLElement* element = node->ToElement();
  777. if ( element
  778. && (!name || XMLUtil::StringEqual( name, element->Name() ))) {
  779. return element;
  780. }
  781. }
  782. return 0;
  783. }
  784. const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const
  785. {
  786. for( const XMLNode* node = _prev; node; node = node->_prev ) {
  787. const XMLElement* element = node->ToElement();
  788. if ( element
  789. && (!name || XMLUtil::StringEqual( name, element->Name() ))) {
  790. return element;
  791. }
  792. }
  793. return 0;
  794. }
  795. char* XMLNode::ParseDeep( char* p, StrPair* parentEnd )
  796. {
  797. // This is a recursive method, but thinking about it "at the current level"
  798. // it is a pretty simple flat list:
  799. // <foo/>
  800. // <!-- comment -->
  801. //
  802. // With a special case:
  803. // <foo>
  804. // </foo>
  805. // <!-- comment -->
  806. //
  807. // Where the closing element (/foo) *must* be the next thing after the opening
  808. // element, and the names must match. BUT the tricky bit is that the closing
  809. // element will be read by the child.
  810. //
  811. // 'endTag' is the end tag for this node, it is returned by a call to a child.
  812. // 'parentEnd' is the end tag for the parent, which is filled in and returned.
  813. while( p && *p ) {
  814. XMLNode* node = 0;
  815. p = _document->Identify( p, &node );
  816. if ( node == 0 ) {
  817. break;
  818. }
  819. StrPair endTag;
  820. p = node->ParseDeep( p, &endTag );
  821. if ( !p ) {
  822. DeleteNode( node );
  823. if ( !_document->Error() ) {
  824. _document->SetError( XML_ERROR_PARSING, 0, 0 );
  825. }
  826. break;
  827. }
  828. XMLDeclaration* decl = node->ToDeclaration();
  829. if ( decl ) {
  830. // A declaration can only be the first child of a document.
  831. // Set error, if document already has children.
  832. if ( !_document->NoChildren() ) {
  833. _document->SetError( XML_ERROR_PARSING_DECLARATION, decl->Value(), 0);
  834. DeleteNode( decl );
  835. break;
  836. }
  837. }
  838. XMLElement* ele = node->ToElement();
  839. if ( ele ) {
  840. // We read the end tag. Return it to the parent.
  841. if ( ele->ClosingType() == XMLElement::CLOSING ) {
  842. if ( parentEnd ) {
  843. ele->_value.TransferTo( parentEnd );
  844. }
  845. node->_memPool->SetTracked(); // created and then immediately deleted.
  846. DeleteNode( node );
  847. return p;
  848. }
  849. // Handle an end tag returned to this level.
  850. // And handle a bunch of annoying errors.
  851. bool mismatch = false;
  852. if ( endTag.Empty() ) {
  853. if ( ele->ClosingType() == XMLElement::OPEN ) {
  854. mismatch = true;
  855. }
  856. }
  857. else {
  858. if ( ele->ClosingType() != XMLElement::OPEN ) {
  859. mismatch = true;
  860. }
  861. else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) {
  862. mismatch = true;
  863. }
  864. }
  865. if ( mismatch ) {
  866. _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, ele->Name(), 0 );
  867. DeleteNode( node );
  868. break;
  869. }
  870. }
  871. InsertEndChild( node );
  872. }
  873. return 0;
  874. }
  875. void XMLNode::DeleteNode( XMLNode* node )
  876. {
  877. if ( node == 0 ) {
  878. return;
  879. }
  880. MemPool* pool = node->_memPool;
  881. node->~XMLNode();
  882. pool->Free( node );
  883. }
  884. void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const
  885. {
  886. TIXMLASSERT( insertThis );
  887. TIXMLASSERT( insertThis->_document == _document );
  888. if ( insertThis->_parent )
  889. insertThis->_parent->Unlink( insertThis );
  890. else
  891. insertThis->_memPool->SetTracked();
  892. }
  893. // --------- XMLText ---------- //
  894. char* XMLText::ParseDeep( char* p, StrPair* )
  895. {
  896. const char* start = p;
  897. if ( this->CData() ) {
  898. p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION );
  899. if ( !p ) {
  900. _document->SetError( XML_ERROR_PARSING_CDATA, start, 0 );
  901. }
  902. return p;
  903. }
  904. else {
  905. int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES;
  906. if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) {
  907. flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING;
  908. }
  909. p = _value.ParseText( p, "<", flags );
  910. if ( p && *p ) {
  911. return p-1;
  912. }
  913. if ( !p ) {
  914. _document->SetError( XML_ERROR_PARSING_TEXT, start, 0 );
  915. }
  916. }
  917. return 0;
  918. }
  919. XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const
  920. {
  921. if ( !doc ) {
  922. doc = _document;
  923. }
  924. XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern?
  925. text->SetCData( this->CData() );
  926. return text;
  927. }
  928. bool XMLText::ShallowEqual( const XMLNode* compare ) const
  929. {
  930. const XMLText* text = compare->ToText();
  931. return ( text && XMLUtil::StringEqual( text->Value(), Value() ) );
  932. }
  933. bool XMLText::Accept( XMLVisitor* visitor ) const
  934. {
  935. TIXMLASSERT( visitor );
  936. return visitor->Visit( *this );
  937. }
  938. // --------- XMLComment ---------- //
  939. XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc )
  940. {
  941. }
  942. XMLComment::~XMLComment()
  943. {
  944. }
  945. char* XMLComment::ParseDeep( char* p, StrPair* )
  946. {
  947. // Comment parses as text.
  948. const char* start = p;
  949. p = _value.ParseText( p, "-->", StrPair::COMMENT );
  950. if ( p == 0 ) {
  951. _document->SetError( XML_ERROR_PARSING_COMMENT, start, 0 );
  952. }
  953. return p;
  954. }
  955. XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const
  956. {
  957. if ( !doc ) {
  958. doc = _document;
  959. }
  960. XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern?
  961. return comment;
  962. }
  963. bool XMLComment::ShallowEqual( const XMLNode* compare ) const
  964. {
  965. TIXMLASSERT( compare );
  966. const XMLComment* comment = compare->ToComment();
  967. return ( comment && XMLUtil::StringEqual( comment->Value(), Value() ));
  968. }
  969. bool XMLComment::Accept( XMLVisitor* visitor ) const
  970. {
  971. TIXMLASSERT( visitor );
  972. return visitor->Visit( *this );
  973. }
  974. // --------- XMLDeclaration ---------- //
  975. XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc )
  976. {
  977. }
  978. XMLDeclaration::~XMLDeclaration()
  979. {
  980. //printf( "~XMLDeclaration\n" );
  981. }
  982. char* XMLDeclaration::ParseDeep( char* p, StrPair* )
  983. {
  984. // Declaration parses as text.
  985. const char* start = p;
  986. p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION );
  987. if ( p == 0 ) {
  988. _document->SetError( XML_ERROR_PARSING_DECLARATION, start, 0 );
  989. }
  990. return p;
  991. }
  992. XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const
  993. {
  994. if ( !doc ) {
  995. doc = _document;
  996. }
  997. XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern?
  998. return dec;
  999. }
  1000. bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const
  1001. {
  1002. TIXMLASSERT( compare );
  1003. const XMLDeclaration* declaration = compare->ToDeclaration();
  1004. return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() ));
  1005. }
  1006. bool XMLDeclaration::Accept( XMLVisitor* visitor ) const
  1007. {
  1008. TIXMLASSERT( visitor );
  1009. return visitor->Visit( *this );
  1010. }
  1011. // --------- XMLUnknown ---------- //
  1012. XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc )
  1013. {
  1014. }
  1015. XMLUnknown::~XMLUnknown()
  1016. {
  1017. }
  1018. char* XMLUnknown::ParseDeep( char* p, StrPair* )
  1019. {
  1020. // Unknown parses as text.
  1021. const char* start = p;
  1022. p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION );
  1023. if ( !p ) {
  1024. _document->SetError( XML_ERROR_PARSING_UNKNOWN, start, 0 );
  1025. }
  1026. return p;
  1027. }
  1028. XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const
  1029. {
  1030. if ( !doc ) {
  1031. doc = _document;
  1032. }
  1033. XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern?
  1034. return text;
  1035. }
  1036. bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const
  1037. {
  1038. TIXMLASSERT( compare );
  1039. const XMLUnknown* unknown = compare->ToUnknown();
  1040. return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() ));
  1041. }
  1042. bool XMLUnknown::Accept( XMLVisitor* visitor ) const
  1043. {
  1044. TIXMLASSERT( visitor );
  1045. return visitor->Visit( *this );
  1046. }
  1047. // --------- XMLAttribute ---------- //
  1048. const char* XMLAttribute::Name() const
  1049. {
  1050. return _name.GetStr();
  1051. }
  1052. const char* XMLAttribute::Value() const
  1053. {
  1054. return _value.GetStr();
  1055. }
  1056. char* XMLAttribute::ParseDeep( char* p, bool processEntities )
  1057. {
  1058. // Parse using the name rules: bug fix, was using ParseText before
  1059. p = _name.ParseName( p );
  1060. if ( !p || !*p ) {
  1061. return 0;
  1062. }
  1063. // Skip white space before =
  1064. p = XMLUtil::SkipWhiteSpace( p );
  1065. if ( *p != '=' ) {
  1066. return 0;
  1067. }
  1068. ++p; // move up to opening quote
  1069. p = XMLUtil::SkipWhiteSpace( p );
  1070. if ( *p != '\"' && *p != '\'' ) {
  1071. return 0;
  1072. }
  1073. char endTag[2] = { *p, 0 };
  1074. ++p; // move past opening quote
  1075. p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES );
  1076. return p;
  1077. }
  1078. void XMLAttribute::SetName( const char* n )
  1079. {
  1080. _name.SetStr( n );
  1081. }
  1082. XMLError XMLAttribute::QueryIntValue( int* value ) const
  1083. {
  1084. if ( XMLUtil::ToInt( Value(), value )) {
  1085. return XML_NO_ERROR;
  1086. }
  1087. return XML_WRONG_ATTRIBUTE_TYPE;
  1088. }
  1089. XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const
  1090. {
  1091. if ( XMLUtil::ToUnsigned( Value(), value )) {
  1092. return XML_NO_ERROR;
  1093. }
  1094. return XML_WRONG_ATTRIBUTE_TYPE;
  1095. }
  1096. XMLError XMLAttribute::QueryBoolValue( bool* value ) const
  1097. {
  1098. if ( XMLUtil::ToBool( Value(), value )) {
  1099. return XML_NO_ERROR;
  1100. }
  1101. return XML_WRONG_ATTRIBUTE_TYPE;
  1102. }
  1103. XMLError XMLAttribute::QueryFloatValue( float* value ) const
  1104. {
  1105. if ( XMLUtil::ToFloat( Value(), value )) {
  1106. return XML_NO_ERROR;
  1107. }
  1108. return XML_WRONG_ATTRIBUTE_TYPE;
  1109. }
  1110. XMLError XMLAttribute::QueryDoubleValue( double* value ) const
  1111. {
  1112. if ( XMLUtil::ToDouble( Value(), value )) {
  1113. return XML_NO_ERROR;
  1114. }
  1115. return XML_WRONG_ATTRIBUTE_TYPE;
  1116. }
  1117. void XMLAttribute::SetAttribute( const char* v )
  1118. {
  1119. _value.SetStr( v );
  1120. }
  1121. void XMLAttribute::SetAttribute( int v )
  1122. {
  1123. char buf[BUF_SIZE];
  1124. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1125. _value.SetStr( buf );
  1126. }
  1127. void XMLAttribute::SetAttribute( unsigned v )
  1128. {
  1129. char buf[BUF_SIZE];
  1130. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1131. _value.SetStr( buf );
  1132. }
  1133. void XMLAttribute::SetAttribute( bool v )
  1134. {
  1135. char buf[BUF_SIZE];
  1136. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1137. _value.SetStr( buf );
  1138. }
  1139. void XMLAttribute::SetAttribute( double v )
  1140. {
  1141. char buf[BUF_SIZE];
  1142. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1143. _value.SetStr( buf );
  1144. }
  1145. void XMLAttribute::SetAttribute( float v )
  1146. {
  1147. char buf[BUF_SIZE];
  1148. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1149. _value.SetStr( buf );
  1150. }
  1151. // --------- XMLElement ---------- //
  1152. XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ),
  1153. _closingType( 0 ),
  1154. _rootAttribute( 0 )
  1155. {
  1156. }
  1157. XMLElement::~XMLElement()
  1158. {
  1159. while( _rootAttribute ) {
  1160. XMLAttribute* next = _rootAttribute->_next;
  1161. DeleteAttribute( _rootAttribute );
  1162. _rootAttribute = next;
  1163. }
  1164. }
  1165. const XMLAttribute* XMLElement::FindAttribute( const char* name ) const
  1166. {
  1167. for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) {
  1168. if ( XMLUtil::StringEqual( a->Name(), name ) ) {
  1169. return a;
  1170. }
  1171. }
  1172. return 0;
  1173. }
  1174. const char* XMLElement::Attribute( const char* name, const char* value ) const
  1175. {
  1176. const XMLAttribute* a = FindAttribute( name );
  1177. if ( !a ) {
  1178. return 0;
  1179. }
  1180. if ( !value || XMLUtil::StringEqual( a->Value(), value )) {
  1181. return a->Value();
  1182. }
  1183. return 0;
  1184. }
  1185. const char* XMLElement::GetText() const
  1186. {
  1187. if ( FirstChild() && FirstChild()->ToText() ) {
  1188. return FirstChild()->Value();
  1189. }
  1190. return 0;
  1191. }
  1192. void XMLElement::SetText( const char* inText )
  1193. {
  1194. if ( FirstChild() && FirstChild()->ToText() )
  1195. FirstChild()->SetValue( inText );
  1196. else {
  1197. XMLText* theText = GetDocument()->NewText( inText );
  1198. InsertFirstChild( theText );
  1199. }
  1200. }
  1201. void XMLElement::SetText( int v )
  1202. {
  1203. char buf[BUF_SIZE];
  1204. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1205. SetText( buf );
  1206. }
  1207. void XMLElement::SetText( unsigned v )
  1208. {
  1209. char buf[BUF_SIZE];
  1210. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1211. SetText( buf );
  1212. }
  1213. void XMLElement::SetText( bool v )
  1214. {
  1215. char buf[BUF_SIZE];
  1216. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1217. SetText( buf );
  1218. }
  1219. void XMLElement::SetText( float v )
  1220. {
  1221. char buf[BUF_SIZE];
  1222. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1223. SetText( buf );
  1224. }
  1225. void XMLElement::SetText( double v )
  1226. {
  1227. char buf[BUF_SIZE];
  1228. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1229. SetText( buf );
  1230. }
  1231. XMLError XMLElement::QueryIntText( int* ival ) const
  1232. {
  1233. if ( FirstChild() && FirstChild()->ToText() ) {
  1234. const char* t = FirstChild()->Value();
  1235. if ( XMLUtil::ToInt( t, ival ) ) {
  1236. return XML_SUCCESS;
  1237. }
  1238. return XML_CAN_NOT_CONVERT_TEXT;
  1239. }
  1240. return XML_NO_TEXT_NODE;
  1241. }
  1242. XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const
  1243. {
  1244. if ( FirstChild() && FirstChild()->ToText() ) {
  1245. const char* t = FirstChild()->Value();
  1246. if ( XMLUtil::ToUnsigned( t, uval ) ) {
  1247. return XML_SUCCESS;
  1248. }
  1249. return XML_CAN_NOT_CONVERT_TEXT;
  1250. }
  1251. return XML_NO_TEXT_NODE;
  1252. }
  1253. XMLError XMLElement::QueryBoolText( bool* bval ) const
  1254. {
  1255. if ( FirstChild() && FirstChild()->ToText() ) {
  1256. const char* t = FirstChild()->Value();
  1257. if ( XMLUtil::ToBool( t, bval ) ) {
  1258. return XML_SUCCESS;
  1259. }
  1260. return XML_CAN_NOT_CONVERT_TEXT;
  1261. }
  1262. return XML_NO_TEXT_NODE;
  1263. }
  1264. XMLError XMLElement::QueryDoubleText( double* dval ) const
  1265. {
  1266. if ( FirstChild() && FirstChild()->ToText() ) {
  1267. const char* t = FirstChild()->Value();
  1268. if ( XMLUtil::ToDouble( t, dval ) ) {
  1269. return XML_SUCCESS;
  1270. }
  1271. return XML_CAN_NOT_CONVERT_TEXT;
  1272. }
  1273. return XML_NO_TEXT_NODE;
  1274. }
  1275. XMLError XMLElement::QueryFloatText( float* fval ) const
  1276. {
  1277. if ( FirstChild() && FirstChild()->ToText() ) {
  1278. const char* t = FirstChild()->Value();
  1279. if ( XMLUtil::ToFloat( t, fval ) ) {
  1280. return XML_SUCCESS;
  1281. }
  1282. return XML_CAN_NOT_CONVERT_TEXT;
  1283. }
  1284. return XML_NO_TEXT_NODE;
  1285. }
  1286. XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name )
  1287. {
  1288. XMLAttribute* last = 0;
  1289. XMLAttribute* attrib = 0;
  1290. for( attrib = _rootAttribute;
  1291. attrib;
  1292. last = attrib, attrib = attrib->_next ) {
  1293. if ( XMLUtil::StringEqual( attrib->Name(), name ) ) {
  1294. break;
  1295. }
  1296. }
  1297. if ( !attrib ) {
  1298. TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() );
  1299. attrib = new (_document->_attributePool.Alloc() ) XMLAttribute();
  1300. attrib->_memPool = &_document->_attributePool;
  1301. if ( last ) {
  1302. last->_next = attrib;
  1303. }
  1304. else {
  1305. _rootAttribute = attrib;
  1306. }
  1307. attrib->SetName( name );
  1308. attrib->_memPool->SetTracked(); // always created and linked.
  1309. }
  1310. return attrib;
  1311. }
  1312. void XMLElement::DeleteAttribute( const char* name )
  1313. {
  1314. XMLAttribute* prev = 0;
  1315. for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) {
  1316. if ( XMLUtil::StringEqual( name, a->Name() ) ) {
  1317. if ( prev ) {
  1318. prev->_next = a->_next;
  1319. }
  1320. else {
  1321. _rootAttribute = a->_next;
  1322. }
  1323. DeleteAttribute( a );
  1324. break;
  1325. }
  1326. prev = a;
  1327. }
  1328. }
  1329. char* XMLElement::ParseAttributes( char* p )
  1330. {
  1331. const char* start = p;
  1332. XMLAttribute* prevAttribute = 0;
  1333. // Read the attributes.
  1334. while( p ) {
  1335. p = XMLUtil::SkipWhiteSpace( p );
  1336. if ( !(*p) ) {
  1337. _document->SetError( XML_ERROR_PARSING_ELEMENT, start, Name() );
  1338. return 0;
  1339. }
  1340. // attribute.
  1341. if (XMLUtil::IsNameStartChar( *p ) ) {
  1342. TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() );
  1343. XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute();
  1344. attrib->_memPool = &_document->_attributePool;
  1345. attrib->_memPool->SetTracked();
  1346. p = attrib->ParseDeep( p, _document->ProcessEntities() );
  1347. if ( !p || Attribute( attrib->Name() ) ) {
  1348. DeleteAttribute( attrib );
  1349. _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, start, p );
  1350. return 0;
  1351. }
  1352. // There is a minor bug here: if the attribute in the source xml
  1353. // document is duplicated, it will not be detected and the
  1354. // attribute will be doubly added. However, tracking the 'prevAttribute'
  1355. // avoids re-scanning the attribute list. Preferring performance for
  1356. // now, may reconsider in the future.
  1357. if ( prevAttribute ) {
  1358. prevAttribute->_next = attrib;
  1359. }
  1360. else {
  1361. _rootAttribute = attrib;
  1362. }
  1363. prevAttribute = attrib;
  1364. }
  1365. // end of the tag
  1366. else if ( *p == '>' ) {
  1367. ++p;
  1368. break;
  1369. }
  1370. // end of the tag
  1371. else if ( *p == '/' && *(p+1) == '>' ) {
  1372. _closingType = CLOSED;
  1373. return p+2; // done; sealed element.
  1374. }
  1375. else {
  1376. _document->SetError( XML_ERROR_PARSING_ELEMENT, start, p );
  1377. return 0;
  1378. }
  1379. }
  1380. return p;
  1381. }
  1382. void XMLElement::DeleteAttribute( XMLAttribute* attribute )
  1383. {
  1384. if ( attribute == 0 ) {
  1385. return;
  1386. }
  1387. MemPool* pool = attribute->_memPool;
  1388. attribute->~XMLAttribute();
  1389. pool->Free( attribute );
  1390. }
  1391. //
  1392. // <ele></ele>
  1393. // <ele>foo<b>bar</b></ele>
  1394. //
  1395. char* XMLElement::ParseDeep( char* p, StrPair* strPair )
  1396. {
  1397. // Read the element name.
  1398. p = XMLUtil::SkipWhiteSpace( p );
  1399. // The closing element is the </element> form. It is
  1400. // parsed just like a regular element then deleted from
  1401. // the DOM.
  1402. if ( *p == '/' ) {
  1403. _closingType = CLOSING;
  1404. ++p;
  1405. }
  1406. p = _value.ParseName( p );
  1407. if ( _value.Empty() ) {
  1408. return 0;
  1409. }
  1410. p = ParseAttributes( p );
  1411. if ( !p || !*p || _closingType ) {
  1412. return p;
  1413. }
  1414. p = XMLNode::ParseDeep( p, strPair );
  1415. return p;
  1416. }
  1417. XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const
  1418. {
  1419. if ( !doc ) {
  1420. doc = _document;
  1421. }
  1422. XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern?
  1423. for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) {
  1424. element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern?
  1425. }
  1426. return element;
  1427. }
  1428. bool XMLElement::ShallowEqual( const XMLNode* compare ) const
  1429. {
  1430. TIXMLASSERT( compare );
  1431. const XMLElement* other = compare->ToElement();
  1432. if ( other && XMLUtil::StringEqual( other->Name(), Name() )) {
  1433. const XMLAttribute* a=FirstAttribute();
  1434. const XMLAttribute* b=other->FirstAttribute();
  1435. while ( a && b ) {
  1436. if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) {
  1437. return false;
  1438. }
  1439. a = a->Next();
  1440. b = b->Next();
  1441. }
  1442. if ( a || b ) {
  1443. // different count
  1444. return false;
  1445. }
  1446. return true;
  1447. }
  1448. return false;
  1449. }
  1450. bool XMLElement::Accept( XMLVisitor* visitor ) const
  1451. {
  1452. TIXMLASSERT( visitor );
  1453. if ( visitor->VisitEnter( *this, _rootAttribute ) ) {
  1454. for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) {
  1455. if ( !node->Accept( visitor ) ) {
  1456. break;
  1457. }
  1458. }
  1459. }
  1460. return visitor->VisitExit( *this );
  1461. }
  1462. // --------- XMLDocument ----------- //
  1463. // Warning: List must match 'enum XMLError'
  1464. const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = {
  1465. "XML_SUCCESS",
  1466. "XML_NO_ATTRIBUTE",
  1467. "XML_WRONG_ATTRIBUTE_TYPE",
  1468. "XML_ERROR_FILE_NOT_FOUND",
  1469. "XML_ERROR_FILE_COULD_NOT_BE_OPENED",
  1470. "XML_ERROR_FILE_READ_ERROR",
  1471. "XML_ERROR_ELEMENT_MISMATCH",
  1472. "XML_ERROR_PARSING_ELEMENT",
  1473. "XML_ERROR_PARSING_ATTRIBUTE",
  1474. "XML_ERROR_IDENTIFYING_TAG",
  1475. "XML_ERROR_PARSING_TEXT",
  1476. "XML_ERROR_PARSING_CDATA",
  1477. "XML_ERROR_PARSING_COMMENT",
  1478. "XML_ERROR_PARSING_DECLARATION",
  1479. "XML_ERROR_PARSING_UNKNOWN",
  1480. "XML_ERROR_EMPTY_DOCUMENT",
  1481. "XML_ERROR_MISMATCHED_ELEMENT",
  1482. "XML_ERROR_PARSING",
  1483. "XML_CAN_NOT_CONVERT_TEXT",
  1484. "XML_NO_TEXT_NODE"
  1485. };
  1486. XMLDocument::XMLDocument( bool processEntities, Whitespace whitespace ) :
  1487. XMLNode( 0 ),
  1488. _writeBOM( false ),
  1489. _processEntities( processEntities ),
  1490. _errorID( XML_NO_ERROR ),
  1491. _whitespace( whitespace ),
  1492. _errorStr1( 0 ),
  1493. _errorStr2( 0 ),
  1494. _charBuffer( 0 )
  1495. {
  1496. // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+)
  1497. _document = this;
  1498. }
  1499. XMLDocument::~XMLDocument()
  1500. {
  1501. Clear();
  1502. }
  1503. void XMLDocument::Clear()
  1504. {
  1505. DeleteChildren();
  1506. #ifdef DEBUG
  1507. const bool hadError = Error();
  1508. #endif
  1509. _errorID = XML_NO_ERROR;
  1510. _errorStr1 = 0;
  1511. _errorStr2 = 0;
  1512. delete [] _charBuffer;
  1513. _charBuffer = 0;
  1514. #if 0
  1515. _textPool.Trace( "text" );
  1516. _elementPool.Trace( "element" );
  1517. _commentPool.Trace( "comment" );
  1518. _attributePool.Trace( "attribute" );
  1519. #endif
  1520. #ifdef DEBUG
  1521. if ( !hadError ) {
  1522. TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() );
  1523. TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() );
  1524. TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() );
  1525. TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() );
  1526. }
  1527. #endif
  1528. }
  1529. XMLElement* XMLDocument::NewElement( const char* name )
  1530. {
  1531. TIXMLASSERT( sizeof( XMLElement ) == _elementPool.ItemSize() );
  1532. XMLElement* ele = new (_elementPool.Alloc()) XMLElement( this );
  1533. ele->_memPool = &_elementPool;
  1534. ele->SetName( name );
  1535. return ele;
  1536. }
  1537. XMLComment* XMLDocument::NewComment( const char* str )
  1538. {
  1539. TIXMLASSERT( sizeof( XMLComment ) == _commentPool.ItemSize() );
  1540. XMLComment* comment = new (_commentPool.Alloc()) XMLComment( this );
  1541. comment->_memPool = &_commentPool;
  1542. comment->SetValue( str );
  1543. return comment;
  1544. }
  1545. XMLText* XMLDocument::NewText( const char* str )
  1546. {
  1547. TIXMLASSERT( sizeof( XMLText ) == _textPool.ItemSize() );
  1548. XMLText* text = new (_textPool.Alloc()) XMLText( this );
  1549. text->_memPool = &_textPool;
  1550. text->SetValue( str );
  1551. return text;
  1552. }
  1553. XMLDeclaration* XMLDocument::NewDeclaration( const char* str )
  1554. {
  1555. TIXMLASSERT( sizeof( XMLDeclaration ) == _commentPool.ItemSize() );
  1556. XMLDeclaration* dec = new (_commentPool.Alloc()) XMLDeclaration( this );
  1557. dec->_memPool = &_commentPool;
  1558. dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" );
  1559. return dec;
  1560. }
  1561. XMLUnknown* XMLDocument::NewUnknown( const char* str )
  1562. {
  1563. TIXMLASSERT( sizeof( XMLUnknown ) == _commentPool.ItemSize() );
  1564. XMLUnknown* unk = new (_commentPool.Alloc()) XMLUnknown( this );
  1565. unk->_memPool = &_commentPool;
  1566. unk->SetValue( str );
  1567. return unk;
  1568. }
  1569. static FILE* callfopen( const char* filepath, const char* mode )
  1570. {
  1571. TIXMLASSERT( filepath );
  1572. TIXMLASSERT( mode );
  1573. #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE)
  1574. FILE* fp = 0;
  1575. errno_t err = fopen_s( &fp, filepath, mode );
  1576. if ( err ) {
  1577. return 0;
  1578. }
  1579. #else
  1580. FILE* fp = fopen( filepath, mode );
  1581. #endif
  1582. return fp;
  1583. }
  1584. void XMLDocument::DeleteNode( XMLNode* node ) {
  1585. TIXMLASSERT( node );
  1586. TIXMLASSERT(node->_document == this );
  1587. if (node->_parent) {
  1588. node->_parent->DeleteChild( node );
  1589. }
  1590. else {
  1591. // Isn't in the tree.
  1592. // Use the parent delete.
  1593. // Also, we need to mark it tracked: we 'know'
  1594. // it was never used.
  1595. node->_memPool->SetTracked();
  1596. // Call the static XMLNode version:
  1597. XMLNode::DeleteNode(node);
  1598. }
  1599. }
  1600. XMLError XMLDocument::LoadFile( const char* filename )
  1601. {
  1602. Clear();
  1603. FILE* fp = callfopen( filename, "rb" );
  1604. if ( !fp ) {
  1605. SetError( XML_ERROR_FILE_NOT_FOUND, filename, 0 );
  1606. return _errorID;
  1607. }
  1608. LoadFile( fp );
  1609. fclose( fp );
  1610. return _errorID;
  1611. }
  1612. // This is likely overengineered template art to have a check that unsigned long value incremented
  1613. // by one still fits into size_t. If size_t type is larger than unsigned long type
  1614. // (x86_64-w64-mingw32 target) then the check is redundant and gcc and clang emit
  1615. // -Wtype-limits warning. This piece makes the compiler select code with a check when a check
  1616. // is useful and code with no check when a check is redundant depending on how size_t and unsigned long
  1617. // types sizes relate to each other.
  1618. template
  1619. <bool = (sizeof(unsigned long) >= sizeof(size_t))>
  1620. struct LongFitsIntoSizeTMinusOne {
  1621. static bool Fits( unsigned long value )
  1622. {
  1623. return value < (size_t)-1;
  1624. }
  1625. };
  1626. template <>
  1627. bool LongFitsIntoSizeTMinusOne<false>::Fits( unsigned long /*value*/ )
  1628. {
  1629. return true;
  1630. }
  1631. XMLError XMLDocument::LoadFile( FILE* fp )
  1632. {
  1633. Clear();
  1634. fseek( fp, 0, SEEK_SET );
  1635. if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) {
  1636. SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
  1637. return _errorID;
  1638. }
  1639. fseek( fp, 0, SEEK_END );
  1640. const long filelength = ftell( fp );
  1641. fseek( fp, 0, SEEK_SET );
  1642. if ( filelength == -1L ) {
  1643. SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
  1644. return _errorID;
  1645. }
  1646. TIXMLASSERT( filelength >= 0 );
  1647. if ( !LongFitsIntoSizeTMinusOne<>::Fits( filelength ) ) {
  1648. // Cannot handle files which won't fit in buffer together with null terminator
  1649. SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
  1650. return _errorID;
  1651. }
  1652. if ( filelength == 0 ) {
  1653. SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
  1654. return _errorID;
  1655. }
  1656. const size_t size = filelength;
  1657. TIXMLASSERT( _charBuffer == 0 );
  1658. _charBuffer = new char[size+1];
  1659. size_t read = fread( _charBuffer, 1, size, fp );
  1660. if ( read != size ) {
  1661. SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
  1662. return _errorID;
  1663. }
  1664. _charBuffer[size] = 0;
  1665. Parse();
  1666. return _errorID;
  1667. }
  1668. XMLError XMLDocument::SaveFile( const char* filename, bool compact )
  1669. {
  1670. FILE* fp = callfopen( filename, "w" );
  1671. if ( !fp ) {
  1672. SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, filename, 0 );
  1673. return _errorID;
  1674. }
  1675. SaveFile(fp, compact);
  1676. fclose( fp );
  1677. return _errorID;
  1678. }
  1679. XMLError XMLDocument::SaveFile( FILE* fp, bool compact )
  1680. {
  1681. // Clear any error from the last save, otherwise it will get reported
  1682. // for *this* call.
  1683. SetError( XML_NO_ERROR, 0, 0 );
  1684. XMLPrinter stream( fp, compact );
  1685. Print( &stream );
  1686. return _errorID;
  1687. }
  1688. XMLError XMLDocument::Parse( const char* p, size_t len )
  1689. {
  1690. Clear();
  1691. if ( len == 0 || !p || !*p ) {
  1692. SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
  1693. return _errorID;
  1694. }
  1695. if ( len == (size_t)(-1) ) {
  1696. len = strlen( p );
  1697. }
  1698. TIXMLASSERT( _charBuffer == 0 );
  1699. _charBuffer = new char[ len+1 ];
  1700. memcpy( _charBuffer, p, len );
  1701. _charBuffer[len] = 0;
  1702. Parse();
  1703. if ( Error() ) {
  1704. // clean up now essentially dangling memory.
  1705. // and the parse fail can put objects in the
  1706. // pools that are dead and inaccessible.
  1707. DeleteChildren();
  1708. _elementPool.Clear();
  1709. _attributePool.Clear();
  1710. _textPool.Clear();
  1711. _commentPool.Clear();
  1712. }
  1713. return _errorID;
  1714. }
  1715. void XMLDocument::Print( XMLPrinter* streamer ) const
  1716. {
  1717. if ( streamer ) {
  1718. Accept( streamer );
  1719. }
  1720. else {
  1721. XMLPrinter stdoutStreamer( stdout );
  1722. Accept( &stdoutStreamer );
  1723. }
  1724. }
  1725. void XMLDocument::SetError( XMLError error, const char* str1, const char* str2 )
  1726. {
  1727. TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT );
  1728. _errorID = error;
  1729. _errorStr1 = str1;
  1730. _errorStr2 = str2;
  1731. }
  1732. const char* XMLDocument::ErrorName() const
  1733. {
  1734. TIXMLASSERT( _errorID >= 0 && _errorID < XML_ERROR_COUNT );
  1735. const char* errorName = _errorNames[_errorID];
  1736. TIXMLASSERT( errorName && errorName[0] );
  1737. return errorName;
  1738. }
  1739. void XMLDocument::PrintError() const
  1740. {
  1741. if ( Error() ) {
  1742. static const int LEN = 20;
  1743. char buf1[LEN] = { 0 };
  1744. char buf2[LEN] = { 0 };
  1745. if ( _errorStr1 ) {
  1746. TIXML_SNPRINTF( buf1, LEN, "%s", _errorStr1 );
  1747. }
  1748. if ( _errorStr2 ) {
  1749. TIXML_SNPRINTF( buf2, LEN, "%s", _errorStr2 );
  1750. }
  1751. // Should check INT_MIN <= _errorID && _errorId <= INT_MAX, but that
  1752. // causes a clang "always true" -Wtautological-constant-out-of-range-compare warning
  1753. TIXMLASSERT( 0 <= _errorID && XML_ERROR_COUNT - 1 <= INT_MAX );
  1754. printf( "XMLDocument error id=%d '%s' str1=%s str2=%s\n",
  1755. static_cast<int>( _errorID ), ErrorName(), buf1, buf2 );
  1756. }
  1757. }
  1758. void XMLDocument::Parse()
  1759. {
  1760. TIXMLASSERT( NoChildren() ); // Clear() must have been called previously
  1761. TIXMLASSERT( _charBuffer );
  1762. char* p = _charBuffer;
  1763. p = XMLUtil::SkipWhiteSpace( p );
  1764. p = const_cast<char*>( XMLUtil::ReadBOM( p, &_writeBOM ) );
  1765. if ( !*p ) {
  1766. SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
  1767. return;
  1768. }
  1769. ParseDeep(p, 0 );
  1770. }
  1771. XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) :
  1772. _elementJustOpened( false ),
  1773. _firstElement( true ),
  1774. _fp( file ),
  1775. _depth( depth ),
  1776. _textDepth( -1 ),
  1777. _processEntities( true ),
  1778. _compactMode( compact )
  1779. {
  1780. for( int i=0; i<ENTITY_RANGE; ++i ) {
  1781. _entityFlag[i] = false;
  1782. _restrictedEntityFlag[i] = false;
  1783. }
  1784. for( int i=0; i<NUM_ENTITIES; ++i ) {
  1785. const char entityValue = entities[i].value;
  1786. TIXMLASSERT( 0 <= entityValue && entityValue < ENTITY_RANGE );
  1787. _entityFlag[ (unsigned char)entityValue ] = true;
  1788. }
  1789. _restrictedEntityFlag[(unsigned char)'&'] = true;
  1790. _restrictedEntityFlag[(unsigned char)'<'] = true;
  1791. _restrictedEntityFlag[(unsigned char)'>'] = true; // not required, but consistency is nice
  1792. _buffer.Push( 0 );
  1793. }
  1794. void XMLPrinter::Print( const char* format, ... )
  1795. {
  1796. va_list va;
  1797. va_start( va, format );
  1798. if ( _fp ) {
  1799. vfprintf( _fp, format, va );
  1800. }
  1801. else {
  1802. const int len = TIXML_VSCPRINTF( format, va );
  1803. // Close out and re-start the va-args
  1804. va_end( va );
  1805. TIXMLASSERT( len >= 0 );
  1806. va_start( va, format );
  1807. TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 );
  1808. char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator.
  1809. TIXML_VSNPRINTF( p, len+1, format, va );
  1810. }
  1811. va_end( va );
  1812. }
  1813. void XMLPrinter::PrintSpace( int depth )
  1814. {
  1815. for( int i=0; i<depth; ++i ) {
  1816. Print( " " );
  1817. }
  1818. }
  1819. void XMLPrinter::PrintString( const char* p, bool restricted )
  1820. {
  1821. // Look for runs of bytes between entities to print.
  1822. const char* q = p;
  1823. if ( _processEntities ) {
  1824. const bool* flag = restricted ? _restrictedEntityFlag : _entityFlag;
  1825. while ( *q ) {
  1826. TIXMLASSERT( p <= q );
  1827. // Remember, char is sometimes signed. (How many times has that bitten me?)
  1828. if ( *q > 0 && *q < ENTITY_RANGE ) {
  1829. // Check for entities. If one is found, flush
  1830. // the stream up until the entity, write the
  1831. // entity, and keep looking.
  1832. if ( flag[(unsigned char)(*q)] ) {
  1833. while ( p < q ) {
  1834. const size_t delta = q - p;
  1835. // %.*s accepts type int as "precision"
  1836. const int toPrint = ( INT_MAX < delta ) ? INT_MAX : (int)delta;
  1837. Print( "%.*s", toPrint, p );
  1838. p += toPrint;
  1839. }
  1840. bool entityPatternPrinted = false;
  1841. for( int i=0; i<NUM_ENTITIES; ++i ) {
  1842. if ( entities[i].value == *q ) {
  1843. Print( "&%s;", entities[i].pattern );
  1844. entityPatternPrinted = true;
  1845. break;
  1846. }
  1847. }
  1848. if ( !entityPatternPrinted ) {
  1849. // TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable in release
  1850. TIXMLASSERT( false );
  1851. }
  1852. ++p;
  1853. }
  1854. }
  1855. ++q;
  1856. TIXMLASSERT( p <= q );
  1857. }
  1858. }
  1859. // Flush the remaining string. This will be the entire
  1860. // string if an entity wasn't found.
  1861. TIXMLASSERT( p <= q );
  1862. if ( !_processEntities || ( p < q ) ) {
  1863. Print( "%s", p );
  1864. }
  1865. }
  1866. void XMLPrinter::PushHeader( bool writeBOM, bool writeDec )
  1867. {
  1868. if ( writeBOM ) {
  1869. static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 };
  1870. Print( "%s", bom );
  1871. }
  1872. if ( writeDec ) {
  1873. PushDeclaration( "xml version=\"1.0\"" );
  1874. }
  1875. }
  1876. void XMLPrinter::OpenElement( const char* name, bool compactMode )
  1877. {
  1878. SealElementIfJustOpened();
  1879. _stack.Push( name );
  1880. if ( _textDepth < 0 && !_firstElement && !compactMode ) {
  1881. Print( "\n" );
  1882. }
  1883. if ( !compactMode ) {
  1884. PrintSpace( _depth );
  1885. }
  1886. Print( "<%s", name );
  1887. _elementJustOpened = true;
  1888. _firstElement = false;
  1889. ++_depth;
  1890. }
  1891. void XMLPrinter::PushAttribute( const char* name, const char* value )
  1892. {
  1893. TIXMLASSERT( _elementJustOpened );
  1894. Print( " %s=\"", name );
  1895. PrintString( value, false );
  1896. Print( "\"" );
  1897. }
  1898. void XMLPrinter::PushAttribute( const char* name, int v )
  1899. {
  1900. char buf[BUF_SIZE];
  1901. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1902. PushAttribute( name, buf );
  1903. }
  1904. void XMLPrinter::PushAttribute( const char* name, unsigned v )
  1905. {
  1906. char buf[BUF_SIZE];
  1907. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1908. PushAttribute( name, buf );
  1909. }
  1910. void XMLPrinter::PushAttribute( const char* name, bool v )
  1911. {
  1912. char buf[BUF_SIZE];
  1913. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1914. PushAttribute( name, buf );
  1915. }
  1916. void XMLPrinter::PushAttribute( const char* name, double v )
  1917. {
  1918. char buf[BUF_SIZE];
  1919. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1920. PushAttribute( name, buf );
  1921. }
  1922. void XMLPrinter::CloseElement( bool compactMode )
  1923. {
  1924. --_depth;
  1925. const char* name = _stack.Pop();
  1926. if ( _elementJustOpened ) {
  1927. Print( "/>" );
  1928. }
  1929. else {
  1930. if ( _textDepth < 0 && !compactMode) {
  1931. Print( "\n" );
  1932. PrintSpace( _depth );
  1933. }
  1934. Print( "</%s>", name );
  1935. }
  1936. if ( _textDepth == _depth ) {
  1937. _textDepth = -1;
  1938. }
  1939. if ( _depth == 0 && !compactMode) {
  1940. Print( "\n" );
  1941. }
  1942. _elementJustOpened = false;
  1943. }
  1944. void XMLPrinter::SealElementIfJustOpened()
  1945. {
  1946. if ( !_elementJustOpened ) {
  1947. return;
  1948. }
  1949. _elementJustOpened = false;
  1950. Print( ">" );
  1951. }
  1952. void XMLPrinter::PushText( const char* text, bool cdata )
  1953. {
  1954. _textDepth = _depth-1;
  1955. SealElementIfJustOpened();
  1956. if ( cdata ) {
  1957. Print( "<![CDATA[%s]]>", text );
  1958. }
  1959. else {
  1960. PrintString( text, true );
  1961. }
  1962. }
  1963. void XMLPrinter::PushText( int value )
  1964. {
  1965. char buf[BUF_SIZE];
  1966. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1967. PushText( buf, false );
  1968. }
  1969. void XMLPrinter::PushText( unsigned value )
  1970. {
  1971. char buf[BUF_SIZE];
  1972. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1973. PushText( buf, false );
  1974. }
  1975. void XMLPrinter::PushText( bool value )
  1976. {
  1977. char buf[BUF_SIZE];
  1978. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1979. PushText( buf, false );
  1980. }
  1981. void XMLPrinter::PushText( float value )
  1982. {
  1983. char buf[BUF_SIZE];
  1984. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1985. PushText( buf, false );
  1986. }
  1987. void XMLPrinter::PushText( double value )
  1988. {
  1989. char buf[BUF_SIZE];
  1990. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1991. PushText( buf, false );
  1992. }
  1993. void XMLPrinter::PushComment( const char* comment )
  1994. {
  1995. SealElementIfJustOpened();
  1996. if ( _textDepth < 0 && !_firstElement && !_compactMode) {
  1997. Print( "\n" );
  1998. PrintSpace( _depth );
  1999. }
  2000. _firstElement = false;
  2001. Print( "<!--%s-->", comment );
  2002. }
  2003. void XMLPrinter::PushDeclaration( const char* value )
  2004. {
  2005. SealElementIfJustOpened();
  2006. if ( _textDepth < 0 && !_firstElement && !_compactMode) {
  2007. Print( "\n" );
  2008. PrintSpace( _depth );
  2009. }
  2010. _firstElement = false;
  2011. Print( "<?%s?>", value );
  2012. }
  2013. void XMLPrinter::PushUnknown( const char* value )
  2014. {
  2015. SealElementIfJustOpened();
  2016. if ( _textDepth < 0 && !_firstElement && !_compactMode) {
  2017. Print( "\n" );
  2018. PrintSpace( _depth );
  2019. }
  2020. _firstElement = false;
  2021. Print( "<!%s>", value );
  2022. }
  2023. bool XMLPrinter::VisitEnter( const XMLDocument& doc )
  2024. {
  2025. _processEntities = doc.ProcessEntities();
  2026. if ( doc.HasBOM() ) {
  2027. PushHeader( true, false );
  2028. }
  2029. return true;
  2030. }
  2031. bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute )
  2032. {
  2033. const XMLElement* parentElem = 0;
  2034. if ( element.Parent() ) {
  2035. parentElem = element.Parent()->ToElement();
  2036. }
  2037. const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode;
  2038. OpenElement( element.Name(), compactMode );
  2039. while ( attribute ) {
  2040. PushAttribute( attribute->Name(), attribute->Value() );
  2041. attribute = attribute->Next();
  2042. }
  2043. return true;
  2044. }
  2045. bool XMLPrinter::VisitExit( const XMLElement& element )
  2046. {
  2047. CloseElement( CompactMode(element) );
  2048. return true;
  2049. }
  2050. bool XMLPrinter::Visit( const XMLText& text )
  2051. {
  2052. PushText( text.Value(), text.CData() );
  2053. return true;
  2054. }
  2055. bool XMLPrinter::Visit( const XMLComment& comment )
  2056. {
  2057. PushComment( comment.Value() );
  2058. return true;
  2059. }
  2060. bool XMLPrinter::Visit( const XMLDeclaration& declaration )
  2061. {
  2062. PushDeclaration( declaration.Value() );
  2063. return true;
  2064. }
  2065. bool XMLPrinter::Visit( const XMLUnknown& unknown )
  2066. {
  2067. PushUnknown( unknown.Value() );
  2068. return true;
  2069. }
  2070. } // namespace tinyxml2