tinyxml2.cpp 74 KB

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