1
0

tinyxml2.cpp 77 KB

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