tinyxml2.cpp 63 KB

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