tinyxml2.cpp 60 KB

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