tinyxml2.cpp 72 KB

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