1
0

tinyxml2.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019
  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 <cstdio>
  20. #include <cstdlib>
  21. #include <new>
  22. #include <cstddef>
  23. using namespace tinyxml2;
  24. static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF
  25. static const char LF = LINE_FEED;
  26. static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out
  27. static const char CR = CARRIAGE_RETURN;
  28. static const char SINGLE_QUOTE = '\'';
  29. static const char DOUBLE_QUOTE = '\"';
  30. // Bunch of unicode info at:
  31. // http://www.unicode.org/faq/utf_bom.html
  32. // ef bb bf (Microsoft "lead bytes") - designates UTF-8
  33. static const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
  34. static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
  35. static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
  36. #define DELETE_NODE( node ) { \
  37. if ( node ) { \
  38. MemPool* pool = node->memPool; \
  39. node->~XMLNode(); \
  40. pool->Free( node ); \
  41. } \
  42. }
  43. #define DELETE_ATTRIBUTE( attrib ) { \
  44. if ( attrib ) { \
  45. MemPool* pool = attrib->memPool; \
  46. attrib->~XMLAttribute(); \
  47. pool->Free( attrib ); \
  48. } \
  49. }
  50. struct Entity {
  51. const char* pattern;
  52. int length;
  53. char value;
  54. };
  55. static const int NUM_ENTITIES = 5;
  56. static const Entity entities[NUM_ENTITIES] =
  57. {
  58. { "quot", 4, DOUBLE_QUOTE },
  59. { "amp", 3, '&' },
  60. { "apos", 4, SINGLE_QUOTE },
  61. { "lt", 2, '<' },
  62. { "gt", 2, '>' }
  63. };
  64. StrPair::~StrPair()
  65. {
  66. Reset();
  67. }
  68. void StrPair::Reset()
  69. {
  70. if ( flags & NEEDS_DELETE ) {
  71. delete [] start;
  72. }
  73. flags = 0;
  74. start = 0;
  75. end = 0;
  76. }
  77. void StrPair::SetStr( const char* str, int flags )
  78. {
  79. Reset();
  80. size_t len = strlen( str );
  81. start = new char[ len+1 ];
  82. memcpy( start, str, len+1 );
  83. end = start + len;
  84. this->flags = flags | NEEDS_DELETE;
  85. }
  86. char* StrPair::ParseText( char* p, const char* endTag, int strFlags )
  87. {
  88. TIXMLASSERT( endTag && *endTag );
  89. char* start = p; // fixme: hides a member
  90. char endChar = *endTag;
  91. size_t length = strlen( endTag );
  92. // Inner loop of text parsing.
  93. while ( *p ) {
  94. if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) {
  95. Set( start, p, strFlags );
  96. return p + length;
  97. }
  98. ++p;
  99. }
  100. return 0;
  101. }
  102. char* StrPair::ParseName( char* p )
  103. {
  104. char* start = p;
  105. if ( !start || !(*start) ) {
  106. return 0;
  107. }
  108. if ( !XMLUtil::IsAlpha( *p ) ) {
  109. return 0;
  110. }
  111. while( *p && (
  112. XMLUtil::IsAlphaNum( (unsigned char) *p )
  113. || *p == '_'
  114. || *p == '-'
  115. || *p == '.'
  116. || *p == ':' ))
  117. {
  118. ++p;
  119. }
  120. if ( p > start ) {
  121. Set( start, p, 0 );
  122. return p;
  123. }
  124. return 0;
  125. }
  126. const char* StrPair::GetStr()
  127. {
  128. if ( flags & NEEDS_FLUSH ) {
  129. *end = 0;
  130. flags ^= NEEDS_FLUSH;
  131. if ( flags ) {
  132. char* p = start; // the read pointer
  133. char* q = start; // the write pointer
  134. while( p < end ) {
  135. if ( (flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) {
  136. // CR-LF pair becomes LF
  137. // CR alone becomes LF
  138. // LF-CR becomes LF
  139. if ( *(p+1) == LF ) {
  140. p += 2;
  141. }
  142. else {
  143. ++p;
  144. }
  145. *q++ = LF;
  146. }
  147. else if ( (flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) {
  148. if ( *(p+1) == CR ) {
  149. p += 2;
  150. }
  151. else {
  152. ++p;
  153. }
  154. *q++ = LF;
  155. }
  156. else if ( (flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) {
  157. // Entities handled by tinyXML2:
  158. // - special entities in the entity table [in/out]
  159. // - numeric character reference [in]
  160. // &#20013; or &#x4e2d;
  161. if ( *(p+1) == '#' ) {
  162. char buf[10] = { 0 };
  163. int len;
  164. p = const_cast<char*>( XMLUtil::GetCharacterRef( p, buf, &len ) );
  165. for( int i=0; i<len; ++i ) {
  166. *q++ = buf[i];
  167. }
  168. TIXMLASSERT( q <= p );
  169. }
  170. else {
  171. int i=0;
  172. for(; i<NUM_ENTITIES; ++i ) {
  173. if ( strncmp( p+1, entities[i].pattern, entities[i].length ) == 0
  174. && *(p+entities[i].length+1) == ';' )
  175. {
  176. // Found an entity convert;
  177. *q = entities[i].value;
  178. ++q;
  179. p += entities[i].length + 2;
  180. break;
  181. }
  182. }
  183. if ( i == NUM_ENTITIES ) {
  184. // fixme: treat as error?
  185. ++p;
  186. ++q;
  187. }
  188. }
  189. }
  190. else {
  191. *q = *p;
  192. ++p;
  193. ++q;
  194. }
  195. }
  196. *q = 0;
  197. }
  198. flags = (flags & NEEDS_DELETE);
  199. }
  200. return start;
  201. }
  202. // --------- XMLUtil ----------- //
  203. const char* XMLUtil::ReadBOM( const char* p, bool* bom )
  204. {
  205. *bom = false;
  206. const unsigned char* pu = reinterpret_cast<const unsigned char*>(p);
  207. // Check for BOM:
  208. if ( *(pu+0) == TIXML_UTF_LEAD_0
  209. && *(pu+1) == TIXML_UTF_LEAD_1
  210. && *(pu+2) == TIXML_UTF_LEAD_2 )
  211. {
  212. *bom = true;
  213. p += 3;
  214. }
  215. return p;
  216. }
  217. void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length )
  218. {
  219. const unsigned long BYTE_MASK = 0xBF;
  220. const unsigned long BYTE_MARK = 0x80;
  221. const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  222. if (input < 0x80)
  223. *length = 1;
  224. else if ( input < 0x800 )
  225. *length = 2;
  226. else if ( input < 0x10000 )
  227. *length = 3;
  228. else if ( input < 0x200000 )
  229. *length = 4;
  230. else
  231. { *length = 0; return; } // This code won't covert this correctly anyway.
  232. output += *length;
  233. // Scary scary fall throughs.
  234. switch (*length)
  235. {
  236. case 4:
  237. --output;
  238. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  239. input >>= 6;
  240. case 3:
  241. --output;
  242. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  243. input >>= 6;
  244. case 2:
  245. --output;
  246. *output = (char)((input | BYTE_MARK) & BYTE_MASK);
  247. input >>= 6;
  248. case 1:
  249. --output;
  250. *output = (char)(input | FIRST_BYTE_MARK[*length]);
  251. }
  252. }
  253. const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length )
  254. {
  255. // Presume an entity, and pull it out.
  256. *length = 0;
  257. if ( *(p+1) == '#' && *(p+2) )
  258. {
  259. unsigned long ucs = 0;
  260. ptrdiff_t delta = 0;
  261. unsigned mult = 1;
  262. if ( *(p+2) == 'x' )
  263. {
  264. // Hexadecimal.
  265. if ( !*(p+3) ) return 0;
  266. const char* q = p+3;
  267. q = strchr( q, ';' );
  268. if ( !q || !*q ) return 0;
  269. delta = q-p;
  270. --q;
  271. while ( *q != 'x' )
  272. {
  273. if ( *q >= '0' && *q <= '9' )
  274. ucs += mult * (*q - '0');
  275. else if ( *q >= 'a' && *q <= 'f' )
  276. ucs += mult * (*q - 'a' + 10);
  277. else if ( *q >= 'A' && *q <= 'F' )
  278. ucs += mult * (*q - 'A' + 10 );
  279. else
  280. return 0;
  281. mult *= 16;
  282. --q;
  283. }
  284. }
  285. else
  286. {
  287. // Decimal.
  288. if ( !*(p+2) ) return 0;
  289. const char* q = p+2;
  290. q = strchr( q, ';' );
  291. if ( !q || !*q ) return 0;
  292. delta = q-p;
  293. --q;
  294. while ( *q != '#' )
  295. {
  296. if ( *q >= '0' && *q <= '9' )
  297. ucs += mult * (*q - '0');
  298. else
  299. return 0;
  300. mult *= 10;
  301. --q;
  302. }
  303. }
  304. // convert the UCS to UTF-8
  305. ConvertUTF32ToUTF8( ucs, value, length );
  306. return p + delta + 1;
  307. }
  308. return p+1;
  309. }
  310. void XMLUtil::ToStr( int v, char* buffer, int bufferSize )
  311. {
  312. TIXML_SNPRINTF( buffer, bufferSize, "%d", v );
  313. }
  314. void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize )
  315. {
  316. TIXML_SNPRINTF( buffer, bufferSize, "%u", v );
  317. }
  318. void XMLUtil::ToStr( bool v, char* buffer, int bufferSize )
  319. {
  320. TIXML_SNPRINTF( buffer, bufferSize, "%d", v ? 1 : 0 );
  321. }
  322. void XMLUtil::ToStr( float v, char* buffer, int bufferSize )
  323. {
  324. TIXML_SNPRINTF( buffer, bufferSize, "%f", v );
  325. }
  326. void XMLUtil::ToStr( double v, char* buffer, int bufferSize )
  327. {
  328. TIXML_SNPRINTF( buffer, bufferSize, "%f", v );
  329. }
  330. bool XMLUtil::ToInt( const char* str, int* value )
  331. {
  332. if ( TIXML_SSCANF( str, "%d", value ) == 1 )
  333. return true;
  334. return false;
  335. }
  336. bool XMLUtil::ToUnsigned( const char* str, unsigned *value )
  337. {
  338. if ( TIXML_SSCANF( str, "%u", value ) == 1 )
  339. return true;
  340. return false;
  341. }
  342. bool XMLUtil::ToBool( const char* str, bool* value )
  343. {
  344. int ival = 0;
  345. if ( ToInt( str, &ival )) {
  346. *value = (ival==0) ? false : true;
  347. return true;
  348. }
  349. if ( StringEqual( str, "true" ) ) {
  350. *value = true;
  351. return true;
  352. }
  353. else if ( StringEqual( str, "false" ) ) {
  354. *value = false;
  355. return true;
  356. }
  357. return false;
  358. }
  359. bool XMLUtil::ToFloat( const char* str, float* value )
  360. {
  361. if ( TIXML_SSCANF( str, "%f", value ) == 1 ) {
  362. return true;
  363. }
  364. return false;
  365. }
  366. bool XMLUtil::ToDouble( const char* str, double* value )
  367. {
  368. if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) {
  369. return true;
  370. }
  371. return false;
  372. }
  373. char* XMLDocument::Identify( char* p, XMLNode** node )
  374. {
  375. XMLNode* returnNode = 0;
  376. char* start = p;
  377. p = XMLUtil::SkipWhiteSpace( p );
  378. if( !p || !*p )
  379. {
  380. return p;
  381. }
  382. // What is this thing?
  383. // - Elements start with a letter or underscore, but xml is reserved.
  384. // - Comments: <!--
  385. // - Decleration: <?
  386. // - Everthing else is unknown to tinyxml.
  387. //
  388. static const char* xmlHeader = { "<?" };
  389. static const char* commentHeader = { "<!--" };
  390. static const char* dtdHeader = { "<!" };
  391. static const char* cdataHeader = { "<![CDATA[" };
  392. static const char* elementHeader = { "<" }; // and a header for everything else; check last.
  393. static const int xmlHeaderLen = 2;
  394. static const int commentHeaderLen = 4;
  395. static const int dtdHeaderLen = 2;
  396. static const int cdataHeaderLen = 9;
  397. static const int elementHeaderLen = 1;
  398. #if defined(_MSC_VER)
  399. #pragma warning ( push )
  400. #pragma warning ( disable : 4127 )
  401. #endif
  402. TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLUnknown ) ); // use same memory pool
  403. TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLDeclaration ) ); // use same memory pool
  404. #if defined(_MSC_VER)
  405. #pragma warning (pop)
  406. #endif
  407. if ( XMLUtil::StringEqual( p, xmlHeader, xmlHeaderLen ) ) {
  408. returnNode = new (commentPool.Alloc()) XMLDeclaration( this );
  409. returnNode->memPool = &commentPool;
  410. p += xmlHeaderLen;
  411. }
  412. else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) {
  413. returnNode = new (commentPool.Alloc()) XMLComment( this );
  414. returnNode->memPool = &commentPool;
  415. p += commentHeaderLen;
  416. }
  417. else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) {
  418. XMLText* text = new (textPool.Alloc()) XMLText( this );
  419. returnNode = text;
  420. returnNode->memPool = &textPool;
  421. p += cdataHeaderLen;
  422. text->SetCData( true );
  423. }
  424. else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) {
  425. returnNode = new (commentPool.Alloc()) XMLUnknown( this );
  426. returnNode->memPool = &commentPool;
  427. p += dtdHeaderLen;
  428. }
  429. else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) {
  430. returnNode = new (elementPool.Alloc()) XMLElement( this );
  431. returnNode->memPool = &elementPool;
  432. p += elementHeaderLen;
  433. }
  434. else {
  435. returnNode = new (textPool.Alloc()) XMLText( this );
  436. returnNode->memPool = &textPool;
  437. p = start; // Back it up, all the text counts.
  438. }
  439. *node = returnNode;
  440. return p;
  441. }
  442. bool XMLDocument::Accept( XMLVisitor* visitor ) const
  443. {
  444. if ( visitor->VisitEnter( *this ) )
  445. {
  446. for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() )
  447. {
  448. if ( !node->Accept( visitor ) )
  449. break;
  450. }
  451. }
  452. return visitor->VisitExit( *this );
  453. }
  454. // --------- XMLNode ----------- //
  455. XMLNode::XMLNode( XMLDocument* doc ) :
  456. document( doc ),
  457. parent( 0 ),
  458. firstChild( 0 ), lastChild( 0 ),
  459. prev( 0 ), next( 0 )
  460. {
  461. }
  462. XMLNode::~XMLNode()
  463. {
  464. DeleteChildren();
  465. if ( parent ) {
  466. parent->Unlink( this );
  467. }
  468. }
  469. void XMLNode::SetValue( const char* str, bool staticMem )
  470. {
  471. if ( staticMem )
  472. value.SetInternedStr( str );
  473. else
  474. value.SetStr( str );
  475. }
  476. void XMLNode::DeleteChildren()
  477. {
  478. while( firstChild ) {
  479. XMLNode* node = firstChild;
  480. Unlink( node );
  481. DELETE_NODE( node );
  482. }
  483. firstChild = lastChild = 0;
  484. }
  485. void XMLNode::Unlink( XMLNode* child )
  486. {
  487. TIXMLASSERT( child->parent == this );
  488. if ( child == firstChild )
  489. firstChild = firstChild->next;
  490. if ( child == lastChild )
  491. lastChild = lastChild->prev;
  492. if ( child->prev ) {
  493. child->prev->next = child->next;
  494. }
  495. if ( child->next ) {
  496. child->next->prev = child->prev;
  497. }
  498. child->parent = 0;
  499. }
  500. void XMLNode::DeleteChild( XMLNode* node )
  501. {
  502. TIXMLASSERT( node->parent == this );
  503. DELETE_NODE( node );
  504. }
  505. XMLNode* XMLNode::InsertEndChild( XMLNode* addThis )
  506. {
  507. if ( lastChild ) {
  508. TIXMLASSERT( firstChild );
  509. TIXMLASSERT( lastChild->next == 0 );
  510. lastChild->next = addThis;
  511. addThis->prev = lastChild;
  512. lastChild = addThis;
  513. addThis->next = 0;
  514. }
  515. else {
  516. TIXMLASSERT( firstChild == 0 );
  517. firstChild = lastChild = addThis;
  518. addThis->prev = 0;
  519. addThis->next = 0;
  520. }
  521. addThis->parent = this;
  522. return addThis;
  523. }
  524. XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis )
  525. {
  526. if ( firstChild ) {
  527. TIXMLASSERT( lastChild );
  528. TIXMLASSERT( firstChild->prev == 0 );
  529. firstChild->prev = addThis;
  530. addThis->next = firstChild;
  531. firstChild = addThis;
  532. addThis->prev = 0;
  533. }
  534. else {
  535. TIXMLASSERT( lastChild == 0 );
  536. firstChild = lastChild = addThis;
  537. addThis->prev = 0;
  538. addThis->next = 0;
  539. }
  540. addThis->parent = this;
  541. return addThis;
  542. }
  543. XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis )
  544. {
  545. TIXMLASSERT( afterThis->parent == this );
  546. if ( afterThis->parent != this )
  547. return 0;
  548. if ( afterThis->next == 0 ) {
  549. // The last node or the only node.
  550. return InsertEndChild( addThis );
  551. }
  552. addThis->prev = afterThis;
  553. addThis->next = afterThis->next;
  554. afterThis->next->prev = addThis;
  555. afterThis->next = addThis;
  556. addThis->parent = this;
  557. return addThis;
  558. }
  559. const XMLElement* XMLNode::FirstChildElement( const char* value ) const
  560. {
  561. for( XMLNode* node=firstChild; node; node=node->next ) {
  562. XMLElement* element = node->ToElement();
  563. if ( element ) {
  564. if ( !value || XMLUtil::StringEqual( element->Name(), value ) ) {
  565. return element;
  566. }
  567. }
  568. }
  569. return 0;
  570. }
  571. const XMLElement* XMLNode::LastChildElement( const char* value ) const
  572. {
  573. for( XMLNode* node=lastChild; node; node=node->prev ) {
  574. XMLElement* element = node->ToElement();
  575. if ( element ) {
  576. if ( !value || XMLUtil::StringEqual( element->Name(), value ) ) {
  577. return element;
  578. }
  579. }
  580. }
  581. return 0;
  582. }
  583. const XMLElement* XMLNode::NextSiblingElement( const char* value ) const
  584. {
  585. for( XMLNode* element=this->next; element; element = element->next ) {
  586. if ( element->ToElement()
  587. && (!value || XMLUtil::StringEqual( value, element->Value() )))
  588. {
  589. return element->ToElement();
  590. }
  591. }
  592. return 0;
  593. }
  594. const XMLElement* XMLNode::PreviousSiblingElement( const char* value ) const
  595. {
  596. for( XMLNode* element=this->prev; element; element = element->prev ) {
  597. if ( element->ToElement()
  598. && (!value || XMLUtil::StringEqual( value, element->Value() )))
  599. {
  600. return element->ToElement();
  601. }
  602. }
  603. return 0;
  604. }
  605. char* XMLNode::ParseDeep( char* p, StrPair* parentEnd )
  606. {
  607. // This is a recursive method, but thinking about it "at the current level"
  608. // it is a pretty simple flat list:
  609. // <foo/>
  610. // <!-- comment -->
  611. //
  612. // With a special case:
  613. // <foo>
  614. // </foo>
  615. // <!-- comment -->
  616. //
  617. // Where the closing element (/foo) *must* be the next thing after the opening
  618. // element, and the names must match. BUT the tricky bit is that the closing
  619. // element will be read by the child.
  620. //
  621. // 'endTag' is the end tag for this node, it is returned by a call to a child.
  622. // 'parentEnd' is the end tag for the parent, which is filled in and returned.
  623. while( p && *p ) {
  624. XMLNode* node = 0;
  625. p = document->Identify( p, &node );
  626. if ( p == 0 || node == 0 ) {
  627. break;
  628. }
  629. StrPair endTag;
  630. p = node->ParseDeep( p, &endTag );
  631. if ( !p ) {
  632. DELETE_NODE( node );
  633. node = 0;
  634. if ( !document->Error() ) {
  635. document->SetError( XML_ERROR_PARSING, 0, 0 );
  636. }
  637. break;
  638. }
  639. // We read the end tag. Return it to the parent.
  640. if ( node->ToElement() && node->ToElement()->ClosingType() == XMLElement::CLOSING ) {
  641. if ( parentEnd ) {
  642. *parentEnd = static_cast<XMLElement*>(node)->value;
  643. }
  644. DELETE_NODE( node );
  645. return p;
  646. }
  647. // Handle an end tag returned to this level.
  648. // And handle a bunch of annoying errors.
  649. XMLElement* ele = node->ToElement();
  650. if ( ele ) {
  651. if ( endTag.Empty() && ele->ClosingType() == XMLElement::OPEN ) {
  652. document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 );
  653. p = 0;
  654. }
  655. else if ( !endTag.Empty() && ele->ClosingType() != XMLElement::OPEN ) {
  656. document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 );
  657. p = 0;
  658. }
  659. else if ( !endTag.Empty() ) {
  660. if ( !XMLUtil::StringEqual( endTag.GetStr(), node->Value() )) {
  661. document->SetError( XML_ERROR_MISMATCHED_ELEMENT, node->Value(), 0 );
  662. p = 0;
  663. }
  664. }
  665. }
  666. if ( p == 0 ) {
  667. DELETE_NODE( node );
  668. node = 0;
  669. }
  670. if ( node ) {
  671. this->InsertEndChild( node );
  672. }
  673. }
  674. return 0;
  675. }
  676. // --------- XMLText ---------- //
  677. char* XMLText::ParseDeep( char* p, StrPair* )
  678. {
  679. const char* start = p;
  680. if ( this->CData() ) {
  681. p = value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION );
  682. if ( !p ) {
  683. document->SetError( XML_ERROR_PARSING_CDATA, start, 0 );
  684. }
  685. return p;
  686. }
  687. else {
  688. p = value.ParseText( p, "<", document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES );
  689. if ( !p ) {
  690. document->SetError( XML_ERROR_PARSING_TEXT, start, 0 );
  691. }
  692. if ( p && *p ) {
  693. return p-1;
  694. }
  695. }
  696. return 0;
  697. }
  698. XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const
  699. {
  700. if ( !doc ) {
  701. doc = document;
  702. }
  703. XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern?
  704. text->SetCData( this->CData() );
  705. return text;
  706. }
  707. bool XMLText::ShallowEqual( const XMLNode* compare ) const
  708. {
  709. return ( compare->ToText() && XMLUtil::StringEqual( compare->ToText()->Value(), Value() ));
  710. }
  711. bool XMLText::Accept( XMLVisitor* visitor ) const
  712. {
  713. return visitor->Visit( *this );
  714. }
  715. // --------- XMLComment ---------- //
  716. XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc )
  717. {
  718. }
  719. XMLComment::~XMLComment()
  720. {
  721. //printf( "~XMLComment\n" );
  722. }
  723. char* XMLComment::ParseDeep( char* p, StrPair* )
  724. {
  725. // Comment parses as text.
  726. const char* start = p;
  727. p = value.ParseText( p, "-->", StrPair::COMMENT );
  728. if ( p == 0 ) {
  729. document->SetError( XML_ERROR_PARSING_COMMENT, start, 0 );
  730. }
  731. return p;
  732. }
  733. XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const
  734. {
  735. if ( !doc ) {
  736. doc = document;
  737. }
  738. XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern?
  739. return comment;
  740. }
  741. bool XMLComment::ShallowEqual( const XMLNode* compare ) const
  742. {
  743. return ( compare->ToComment() && XMLUtil::StringEqual( compare->ToComment()->Value(), Value() ));
  744. }
  745. bool XMLComment::Accept( XMLVisitor* visitor ) const
  746. {
  747. return visitor->Visit( *this );
  748. }
  749. // --------- XMLDeclaration ---------- //
  750. XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc )
  751. {
  752. }
  753. XMLDeclaration::~XMLDeclaration()
  754. {
  755. //printf( "~XMLDeclaration\n" );
  756. }
  757. char* XMLDeclaration::ParseDeep( char* p, StrPair* )
  758. {
  759. // Declaration parses as text.
  760. const char* start = p;
  761. p = value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION );
  762. if ( p == 0 ) {
  763. document->SetError( XML_ERROR_PARSING_DECLARATION, start, 0 );
  764. }
  765. return p;
  766. }
  767. XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const
  768. {
  769. if ( !doc ) {
  770. doc = document;
  771. }
  772. XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern?
  773. return dec;
  774. }
  775. bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const
  776. {
  777. return ( compare->ToDeclaration() && XMLUtil::StringEqual( compare->ToDeclaration()->Value(), Value() ));
  778. }
  779. bool XMLDeclaration::Accept( XMLVisitor* visitor ) const
  780. {
  781. return visitor->Visit( *this );
  782. }
  783. // --------- XMLUnknown ---------- //
  784. XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc )
  785. {
  786. }
  787. XMLUnknown::~XMLUnknown()
  788. {
  789. }
  790. char* XMLUnknown::ParseDeep( char* p, StrPair* )
  791. {
  792. // Unknown parses as text.
  793. const char* start = p;
  794. p = value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION );
  795. if ( !p ) {
  796. document->SetError( XML_ERROR_PARSING_UNKNOWN, start, 0 );
  797. }
  798. return p;
  799. }
  800. XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const
  801. {
  802. if ( !doc ) {
  803. doc = document;
  804. }
  805. XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern?
  806. return text;
  807. }
  808. bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const
  809. {
  810. return ( compare->ToUnknown() && XMLUtil::StringEqual( compare->ToUnknown()->Value(), Value() ));
  811. }
  812. bool XMLUnknown::Accept( XMLVisitor* visitor ) const
  813. {
  814. return visitor->Visit( *this );
  815. }
  816. // --------- XMLAttribute ---------- //
  817. char* XMLAttribute::ParseDeep( char* p, bool processEntities )
  818. {
  819. // Parse using the name rules: bug fix, was using ParseText before
  820. p = name.ParseName( p );
  821. if ( !p || !*p ) return 0;
  822. // Skip white space before =
  823. p = XMLUtil::SkipWhiteSpace( p );
  824. if ( !p || *p != '=' ) return 0;
  825. ++p; // move up to opening quote
  826. p = XMLUtil::SkipWhiteSpace( p );
  827. if ( *p != '\"' && *p != '\'' ) return 0;
  828. char endTag[2] = { *p, 0 };
  829. ++p; // move past opening quote
  830. p = value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES );
  831. return p;
  832. }
  833. void XMLAttribute::SetName( const char* n )
  834. {
  835. name.SetStr( n );
  836. }
  837. int XMLAttribute::QueryIntValue( int* value ) const
  838. {
  839. if ( XMLUtil::ToInt( Value(), value ))
  840. return XML_NO_ERROR;
  841. return XML_WRONG_ATTRIBUTE_TYPE;
  842. }
  843. int XMLAttribute::QueryUnsignedValue( unsigned int* value ) const
  844. {
  845. if ( XMLUtil::ToUnsigned( Value(), value ))
  846. return XML_NO_ERROR;
  847. return XML_WRONG_ATTRIBUTE_TYPE;
  848. }
  849. int XMLAttribute::QueryBoolValue( bool* value ) const
  850. {
  851. if ( XMLUtil::ToBool( Value(), value )) {
  852. return XML_NO_ERROR;
  853. }
  854. return XML_WRONG_ATTRIBUTE_TYPE;
  855. }
  856. int XMLAttribute::QueryFloatValue( float* value ) const
  857. {
  858. if ( XMLUtil::ToFloat( Value(), value ))
  859. return XML_NO_ERROR;
  860. return XML_WRONG_ATTRIBUTE_TYPE;
  861. }
  862. int XMLAttribute::QueryDoubleValue( double* value ) const
  863. {
  864. if ( XMLUtil::ToDouble( Value(), value ))
  865. return XML_NO_ERROR;
  866. return XML_WRONG_ATTRIBUTE_TYPE;
  867. }
  868. void XMLAttribute::SetAttribute( const char* v )
  869. {
  870. value.SetStr( v );
  871. }
  872. void XMLAttribute::SetAttribute( int v )
  873. {
  874. char buf[BUF_SIZE];
  875. XMLUtil::ToStr( v, buf, BUF_SIZE );
  876. value.SetStr( buf );
  877. }
  878. void XMLAttribute::SetAttribute( unsigned v )
  879. {
  880. char buf[BUF_SIZE];
  881. XMLUtil::ToStr( v, buf, BUF_SIZE );
  882. value.SetStr( buf );
  883. }
  884. void XMLAttribute::SetAttribute( bool v )
  885. {
  886. char buf[BUF_SIZE];
  887. XMLUtil::ToStr( v, buf, BUF_SIZE );
  888. value.SetStr( buf );
  889. }
  890. void XMLAttribute::SetAttribute( double v )
  891. {
  892. char buf[BUF_SIZE];
  893. XMLUtil::ToStr( v, buf, BUF_SIZE );
  894. value.SetStr( buf );
  895. }
  896. void XMLAttribute::SetAttribute( float v )
  897. {
  898. char buf[BUF_SIZE];
  899. XMLUtil::ToStr( v, buf, BUF_SIZE );
  900. value.SetStr( buf );
  901. }
  902. // --------- XMLElement ---------- //
  903. XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ),
  904. closingType( 0 ),
  905. rootAttribute( 0 )
  906. {
  907. }
  908. XMLElement::~XMLElement()
  909. {
  910. while( rootAttribute ) {
  911. XMLAttribute* next = rootAttribute->next;
  912. DELETE_ATTRIBUTE( rootAttribute );
  913. rootAttribute = next;
  914. }
  915. }
  916. XMLAttribute* XMLElement::FindAttribute( const char* name )
  917. {
  918. XMLAttribute* a = 0;
  919. for( a=rootAttribute; a; a = a->next ) {
  920. if ( XMLUtil::StringEqual( a->Name(), name ) )
  921. return a;
  922. }
  923. return 0;
  924. }
  925. const XMLAttribute* XMLElement::FindAttribute( const char* name ) const
  926. {
  927. XMLAttribute* a = 0;
  928. for( a=rootAttribute; a; a = a->next ) {
  929. if ( XMLUtil::StringEqual( a->Name(), name ) )
  930. return a;
  931. }
  932. return 0;
  933. }
  934. const char* XMLElement::Attribute( const char* name, const char* value ) const
  935. {
  936. const XMLAttribute* a = FindAttribute( name );
  937. if ( !a )
  938. return 0;
  939. if ( !value || XMLUtil::StringEqual( a->Value(), value ))
  940. return a->Value();
  941. return 0;
  942. }
  943. const char* XMLElement::GetText() const
  944. {
  945. if ( FirstChild() && FirstChild()->ToText() ) {
  946. return FirstChild()->ToText()->Value();
  947. }
  948. return 0;
  949. }
  950. int XMLElement::QueryIntText( int* _value ) const
  951. {
  952. if ( FirstChild() && FirstChild()->ToText() ) {
  953. const char* t = FirstChild()->ToText()->Value();
  954. if ( XMLUtil::ToInt( t, _value ) ) {
  955. return XML_SUCCESS;
  956. }
  957. return XML_CAN_NOT_CONVERT_TEXT;
  958. }
  959. return XML_NO_TEXT_NODE;
  960. }
  961. int XMLElement::QueryUnsignedText( unsigned* _value ) const
  962. {
  963. if ( FirstChild() && FirstChild()->ToText() ) {
  964. const char* t = FirstChild()->ToText()->Value();
  965. if ( XMLUtil::ToUnsigned( t, _value ) ) {
  966. return XML_SUCCESS;
  967. }
  968. return XML_CAN_NOT_CONVERT_TEXT;
  969. }
  970. return XML_NO_TEXT_NODE;
  971. }
  972. int XMLElement::QueryBoolText( bool* _value ) const
  973. {
  974. if ( FirstChild() && FirstChild()->ToText() ) {
  975. const char* t = FirstChild()->ToText()->Value();
  976. if ( XMLUtil::ToBool( t, _value ) ) {
  977. return XML_SUCCESS;
  978. }
  979. return XML_CAN_NOT_CONVERT_TEXT;
  980. }
  981. return XML_NO_TEXT_NODE;
  982. }
  983. int XMLElement::QueryDoubleText( double* _value ) const
  984. {
  985. if ( FirstChild() && FirstChild()->ToText() ) {
  986. const char* t = FirstChild()->ToText()->Value();
  987. if ( XMLUtil::ToDouble( t, _value ) ) {
  988. return XML_SUCCESS;
  989. }
  990. return XML_CAN_NOT_CONVERT_TEXT;
  991. }
  992. return XML_NO_TEXT_NODE;
  993. }
  994. int XMLElement::QueryFloatText( float* _value ) const
  995. {
  996. if ( FirstChild() && FirstChild()->ToText() ) {
  997. const char* t = FirstChild()->ToText()->Value();
  998. if ( XMLUtil::ToFloat( t, _value ) ) {
  999. return XML_SUCCESS;
  1000. }
  1001. return XML_CAN_NOT_CONVERT_TEXT;
  1002. }
  1003. return XML_NO_TEXT_NODE;
  1004. }
  1005. XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name )
  1006. {
  1007. XMLAttribute* last = 0;
  1008. XMLAttribute* attrib = 0;
  1009. for( attrib = rootAttribute;
  1010. attrib;
  1011. last = attrib, attrib = attrib->next )
  1012. {
  1013. if ( XMLUtil::StringEqual( attrib->Name(), name ) ) {
  1014. break;
  1015. }
  1016. }
  1017. if ( !attrib ) {
  1018. attrib = new (document->attributePool.Alloc() ) XMLAttribute();
  1019. attrib->memPool = &document->attributePool;
  1020. if ( last ) {
  1021. last->next = attrib;
  1022. }
  1023. else {
  1024. rootAttribute = attrib;
  1025. }
  1026. attrib->SetName( name );
  1027. }
  1028. return attrib;
  1029. }
  1030. void XMLElement::DeleteAttribute( const char* name )
  1031. {
  1032. XMLAttribute* prev = 0;
  1033. for( XMLAttribute* a=rootAttribute; a; a=a->next ) {
  1034. if ( XMLUtil::StringEqual( name, a->Name() ) ) {
  1035. if ( prev ) {
  1036. prev->next = a->next;
  1037. }
  1038. else {
  1039. rootAttribute = a->next;
  1040. }
  1041. DELETE_ATTRIBUTE( a );
  1042. break;
  1043. }
  1044. prev = a;
  1045. }
  1046. }
  1047. char* XMLElement::ParseAttributes( char* p )
  1048. {
  1049. const char* start = p;
  1050. XMLAttribute* prevAttribute = 0;
  1051. // Read the attributes.
  1052. while( p ) {
  1053. p = XMLUtil::SkipWhiteSpace( p );
  1054. if ( !p || !(*p) ) {
  1055. document->SetError( XML_ERROR_PARSING_ELEMENT, start, Name() );
  1056. return 0;
  1057. }
  1058. // attribute.
  1059. if ( XMLUtil::IsAlpha( *p ) ) {
  1060. XMLAttribute* attrib = new (document->attributePool.Alloc() ) XMLAttribute();
  1061. attrib->memPool = &document->attributePool;
  1062. p = attrib->ParseDeep( p, document->ProcessEntities() );
  1063. if ( !p || Attribute( attrib->Name() ) ) {
  1064. DELETE_ATTRIBUTE( attrib );
  1065. document->SetError( XML_ERROR_PARSING_ATTRIBUTE, start, p );
  1066. return 0;
  1067. }
  1068. // There is a minor bug here: if the attribute in the source xml
  1069. // document is duplicated, it will not be detected and the
  1070. // attribute will be doubly added. However, tracking the 'prevAttribute'
  1071. // avoids re-scanning the attribute list. Preferring performance for
  1072. // now, may reconsider in the future.
  1073. if ( prevAttribute ) {
  1074. prevAttribute->next = attrib;
  1075. }
  1076. else {
  1077. rootAttribute = attrib;
  1078. }
  1079. prevAttribute = attrib;
  1080. }
  1081. // end of the tag
  1082. else if ( *p == '/' && *(p+1) == '>' ) {
  1083. closingType = CLOSED;
  1084. return p+2; // done; sealed element.
  1085. }
  1086. // end of the tag
  1087. else if ( *p == '>' ) {
  1088. ++p;
  1089. break;
  1090. }
  1091. else {
  1092. document->SetError( XML_ERROR_PARSING_ELEMENT, start, p );
  1093. return 0;
  1094. }
  1095. }
  1096. return p;
  1097. }
  1098. //
  1099. // <ele></ele>
  1100. // <ele>foo<b>bar</b></ele>
  1101. //
  1102. char* XMLElement::ParseDeep( char* p, StrPair* strPair )
  1103. {
  1104. // Read the element name.
  1105. p = XMLUtil::SkipWhiteSpace( p );
  1106. if ( !p ) return 0;
  1107. // The closing element is the </element> form. It is
  1108. // parsed just like a regular element then deleted from
  1109. // the DOM.
  1110. if ( *p == '/' ) {
  1111. closingType = CLOSING;
  1112. ++p;
  1113. }
  1114. p = value.ParseName( p );
  1115. if ( value.Empty() ) return 0;
  1116. p = ParseAttributes( p );
  1117. if ( !p || !*p || closingType )
  1118. return p;
  1119. p = XMLNode::ParseDeep( p, strPair );
  1120. return p;
  1121. }
  1122. XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const
  1123. {
  1124. if ( !doc ) {
  1125. doc = document;
  1126. }
  1127. XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern?
  1128. for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) {
  1129. element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern?
  1130. }
  1131. return element;
  1132. }
  1133. bool XMLElement::ShallowEqual( const XMLNode* compare ) const
  1134. {
  1135. const XMLElement* other = compare->ToElement();
  1136. if ( other && XMLUtil::StringEqual( other->Value(), Value() )) {
  1137. const XMLAttribute* a=FirstAttribute();
  1138. const XMLAttribute* b=other->FirstAttribute();
  1139. while ( a && b ) {
  1140. if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) {
  1141. return false;
  1142. }
  1143. a = a->Next();
  1144. b = b->Next();
  1145. }
  1146. if ( a || b ) {
  1147. // different count
  1148. return false;
  1149. }
  1150. return true;
  1151. }
  1152. return false;
  1153. }
  1154. bool XMLElement::Accept( XMLVisitor* visitor ) const
  1155. {
  1156. if ( visitor->VisitEnter( *this, rootAttribute ) )
  1157. {
  1158. for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() )
  1159. {
  1160. if ( !node->Accept( visitor ) )
  1161. break;
  1162. }
  1163. }
  1164. return visitor->VisitExit( *this );
  1165. }
  1166. // --------- XMLDocument ----------- //
  1167. XMLDocument::XMLDocument( bool _processEntities ) :
  1168. XMLNode( 0 ),
  1169. writeBOM( false ),
  1170. processEntities( _processEntities ),
  1171. errorID( 0 ),
  1172. errorStr1( 0 ),
  1173. errorStr2( 0 ),
  1174. charBuffer( 0 )
  1175. {
  1176. document = this; // avoid warning about 'this' in initializer list
  1177. }
  1178. XMLDocument::~XMLDocument()
  1179. {
  1180. DeleteChildren();
  1181. delete [] charBuffer;
  1182. #if 0
  1183. textPool.Trace( "text" );
  1184. elementPool.Trace( "element" );
  1185. commentPool.Trace( "comment" );
  1186. attributePool.Trace( "attribute" );
  1187. #endif
  1188. TIXMLASSERT( textPool.CurrentAllocs() == 0 );
  1189. TIXMLASSERT( elementPool.CurrentAllocs() == 0 );
  1190. TIXMLASSERT( commentPool.CurrentAllocs() == 0 );
  1191. TIXMLASSERT( attributePool.CurrentAllocs() == 0 );
  1192. }
  1193. void XMLDocument::InitDocument()
  1194. {
  1195. errorID = XML_NO_ERROR;
  1196. errorStr1 = 0;
  1197. errorStr2 = 0;
  1198. delete [] charBuffer;
  1199. charBuffer = 0;
  1200. }
  1201. XMLElement* XMLDocument::NewElement( const char* name )
  1202. {
  1203. XMLElement* ele = new (elementPool.Alloc()) XMLElement( this );
  1204. ele->memPool = &elementPool;
  1205. ele->SetName( name );
  1206. return ele;
  1207. }
  1208. XMLComment* XMLDocument::NewComment( const char* str )
  1209. {
  1210. XMLComment* comment = new (commentPool.Alloc()) XMLComment( this );
  1211. comment->memPool = &commentPool;
  1212. comment->SetValue( str );
  1213. return comment;
  1214. }
  1215. XMLText* XMLDocument::NewText( const char* str )
  1216. {
  1217. XMLText* text = new (textPool.Alloc()) XMLText( this );
  1218. text->memPool = &textPool;
  1219. text->SetValue( str );
  1220. return text;
  1221. }
  1222. XMLDeclaration* XMLDocument::NewDeclaration( const char* str )
  1223. {
  1224. XMLDeclaration* dec = new (commentPool.Alloc()) XMLDeclaration( this );
  1225. dec->memPool = &commentPool;
  1226. dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" );
  1227. return dec;
  1228. }
  1229. XMLUnknown* XMLDocument::NewUnknown( const char* str )
  1230. {
  1231. XMLUnknown* unk = new (commentPool.Alloc()) XMLUnknown( this );
  1232. unk->memPool = &commentPool;
  1233. unk->SetValue( str );
  1234. return unk;
  1235. }
  1236. int XMLDocument::LoadFile( const char* filename )
  1237. {
  1238. DeleteChildren();
  1239. InitDocument();
  1240. #if defined(_MSC_VER)
  1241. #pragma warning ( push )
  1242. #pragma warning ( disable : 4996 ) // Fail to see a compelling reason why this should be deprecated.
  1243. #endif
  1244. FILE* fp = fopen( filename, "rb" );
  1245. #if defined(_MSC_VER)
  1246. #pragma warning ( pop )
  1247. #endif
  1248. if ( !fp ) {
  1249. SetError( XML_ERROR_FILE_NOT_FOUND, filename, 0 );
  1250. return errorID;
  1251. }
  1252. LoadFile( fp );
  1253. fclose( fp );
  1254. return errorID;
  1255. }
  1256. int XMLDocument::LoadFile( FILE* fp )
  1257. {
  1258. DeleteChildren();
  1259. InitDocument();
  1260. fseek( fp, 0, SEEK_END );
  1261. unsigned size = ftell( fp );
  1262. fseek( fp, 0, SEEK_SET );
  1263. if ( size == 0 ) {
  1264. return errorID;
  1265. }
  1266. charBuffer = new char[size+1];
  1267. size_t read = fread( charBuffer, 1, size, fp );
  1268. if ( read != size ) {
  1269. SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 );
  1270. return errorID;
  1271. }
  1272. charBuffer[size] = 0;
  1273. const char* p = charBuffer;
  1274. p = XMLUtil::SkipWhiteSpace( p );
  1275. p = XMLUtil::ReadBOM( p, &writeBOM );
  1276. if ( !p || !*p ) {
  1277. SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
  1278. return errorID;
  1279. }
  1280. ParseDeep( charBuffer + (p-charBuffer), 0 );
  1281. return errorID;
  1282. }
  1283. int XMLDocument::SaveFile( const char* filename )
  1284. {
  1285. #if defined(_MSC_VER)
  1286. #pragma warning ( push )
  1287. #pragma warning ( disable : 4996 ) // Fail to see a compelling reason why this should be deprecated.
  1288. #endif
  1289. FILE* fp = fopen( filename, "w" );
  1290. #if defined(_MSC_VER)
  1291. #pragma warning ( pop )
  1292. #endif
  1293. if ( !fp ) {
  1294. SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, filename, 0 );
  1295. return errorID;
  1296. }
  1297. SaveFile(fp);
  1298. fclose( fp );
  1299. return errorID;
  1300. }
  1301. int XMLDocument::SaveFile( FILE* fp )
  1302. {
  1303. XMLPrinter stream( fp );
  1304. Print( &stream );
  1305. return errorID;
  1306. }
  1307. int XMLDocument::Parse( const char* p )
  1308. {
  1309. DeleteChildren();
  1310. InitDocument();
  1311. if ( !p || !*p ) {
  1312. SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
  1313. return errorID;
  1314. }
  1315. p = XMLUtil::SkipWhiteSpace( p );
  1316. p = XMLUtil::ReadBOM( p, &writeBOM );
  1317. if ( !p || !*p ) {
  1318. SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 );
  1319. return errorID;
  1320. }
  1321. size_t len = strlen( p );
  1322. charBuffer = new char[ len+1 ];
  1323. memcpy( charBuffer, p, len+1 );
  1324. ParseDeep( charBuffer, 0 );
  1325. return errorID;
  1326. }
  1327. void XMLDocument::Print( XMLPrinter* streamer )
  1328. {
  1329. XMLPrinter stdStreamer( stdout );
  1330. if ( !streamer )
  1331. streamer = &stdStreamer;
  1332. Accept( streamer );
  1333. }
  1334. void XMLDocument::SetError( int error, const char* str1, const char* str2 )
  1335. {
  1336. errorID = error;
  1337. errorStr1 = str1;
  1338. errorStr2 = str2;
  1339. }
  1340. void XMLDocument::PrintError() const
  1341. {
  1342. if ( errorID ) {
  1343. static const int LEN = 20;
  1344. char buf1[LEN] = { 0 };
  1345. char buf2[LEN] = { 0 };
  1346. if ( errorStr1 ) {
  1347. TIXML_SNPRINTF( buf1, LEN, "%s", errorStr1 );
  1348. }
  1349. if ( errorStr2 ) {
  1350. TIXML_SNPRINTF( buf2, LEN, "%s", errorStr2 );
  1351. }
  1352. printf( "XMLDocument error id=%d str1=%s str2=%s\n",
  1353. errorID, buf1, buf2 );
  1354. }
  1355. }
  1356. XMLPrinter::XMLPrinter( FILE* file, bool compact ) :
  1357. elementJustOpened( false ),
  1358. firstElement( true ),
  1359. fp( file ),
  1360. depth( 0 ),
  1361. textDepth( -1 ),
  1362. processEntities( true ),
  1363. compactMode( compact )
  1364. {
  1365. for( int i=0; i<ENTITY_RANGE; ++i ) {
  1366. entityFlag[i] = false;
  1367. restrictedEntityFlag[i] = false;
  1368. }
  1369. for( int i=0; i<NUM_ENTITIES; ++i ) {
  1370. TIXMLASSERT( entities[i].value < ENTITY_RANGE );
  1371. if ( entities[i].value < ENTITY_RANGE ) {
  1372. entityFlag[ (int)entities[i].value ] = true;
  1373. }
  1374. }
  1375. restrictedEntityFlag[(int)'&'] = true;
  1376. restrictedEntityFlag[(int)'<'] = true;
  1377. restrictedEntityFlag[(int)'>'] = true; // not required, but consistency is nice
  1378. buffer.Push( 0 );
  1379. }
  1380. void XMLPrinter::Print( const char* format, ... )
  1381. {
  1382. va_list va;
  1383. va_start( va, format );
  1384. if ( fp ) {
  1385. vfprintf( fp, format, va );
  1386. }
  1387. else {
  1388. // This seems brutally complex. Haven't figured out a better
  1389. // way on windows.
  1390. #ifdef _MSC_VER
  1391. int len = -1;
  1392. int expand = 1000;
  1393. while ( len < 0 ) {
  1394. len = vsnprintf_s( accumulator.Mem(), accumulator.Capacity(), _TRUNCATE, format, va );
  1395. if ( len < 0 ) {
  1396. expand *= 3/2;
  1397. accumulator.PushArr( expand );
  1398. }
  1399. }
  1400. char* p = buffer.PushArr( len ) - 1;
  1401. memcpy( p, accumulator.Mem(), len+1 );
  1402. #else
  1403. int len = vsnprintf( 0, 0, format, va );
  1404. // Close out and re-start the va-args
  1405. va_end( va );
  1406. va_start( va, format );
  1407. char* p = buffer.PushArr( len ) - 1;
  1408. vsnprintf( p, len+1, format, va );
  1409. #endif
  1410. }
  1411. va_end( va );
  1412. }
  1413. void XMLPrinter::PrintSpace( int depth )
  1414. {
  1415. for( int i=0; i<depth; ++i ) {
  1416. Print( " " );
  1417. }
  1418. }
  1419. void XMLPrinter::PrintString( const char* p, bool restricted )
  1420. {
  1421. // Look for runs of bytes between entities to print.
  1422. const char* q = p;
  1423. const bool* flag = restricted ? restrictedEntityFlag : entityFlag;
  1424. if ( processEntities ) {
  1425. while ( *q ) {
  1426. // Remember, char is sometimes signed. (How many times has that bitten me?)
  1427. if ( *q > 0 && *q < ENTITY_RANGE ) {
  1428. // Check for entities. If one is found, flush
  1429. // the stream up until the entity, write the
  1430. // entity, and keep looking.
  1431. if ( flag[(unsigned)(*q)] ) {
  1432. while ( p < q ) {
  1433. Print( "%c", *p );
  1434. ++p;
  1435. }
  1436. for( int i=0; i<NUM_ENTITIES; ++i ) {
  1437. if ( entities[i].value == *q ) {
  1438. Print( "&%s;", entities[i].pattern );
  1439. break;
  1440. }
  1441. }
  1442. ++p;
  1443. }
  1444. }
  1445. ++q;
  1446. }
  1447. }
  1448. // Flush the remaining string. This will be the entire
  1449. // string if an entity wasn't found.
  1450. if ( !processEntities || (q-p > 0) ) {
  1451. Print( "%s", p );
  1452. }
  1453. }
  1454. void XMLPrinter::PushHeader( bool writeBOM, bool writeDec )
  1455. {
  1456. static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 };
  1457. if ( writeBOM ) {
  1458. Print( "%s", bom );
  1459. }
  1460. if ( writeDec ) {
  1461. PushDeclaration( "xml version=\"1.0\"" );
  1462. }
  1463. }
  1464. void XMLPrinter::OpenElement( const char* name )
  1465. {
  1466. if ( elementJustOpened ) {
  1467. SealElement();
  1468. }
  1469. stack.Push( name );
  1470. if ( textDepth < 0 && !firstElement && !compactMode ) {
  1471. Print( "\n" );
  1472. PrintSpace( depth );
  1473. }
  1474. Print( "<%s", name );
  1475. elementJustOpened = true;
  1476. firstElement = false;
  1477. ++depth;
  1478. }
  1479. void XMLPrinter::PushAttribute( const char* name, const char* value )
  1480. {
  1481. TIXMLASSERT( elementJustOpened );
  1482. Print( " %s=\"", name );
  1483. PrintString( value, false );
  1484. Print( "\"" );
  1485. }
  1486. void XMLPrinter::PushAttribute( const char* name, int v )
  1487. {
  1488. char buf[BUF_SIZE];
  1489. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1490. PushAttribute( name, buf );
  1491. }
  1492. void XMLPrinter::PushAttribute( const char* name, unsigned v )
  1493. {
  1494. char buf[BUF_SIZE];
  1495. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1496. PushAttribute( name, buf );
  1497. }
  1498. void XMLPrinter::PushAttribute( const char* name, bool v )
  1499. {
  1500. char buf[BUF_SIZE];
  1501. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1502. PushAttribute( name, buf );
  1503. }
  1504. void XMLPrinter::PushAttribute( const char* name, double v )
  1505. {
  1506. char buf[BUF_SIZE];
  1507. XMLUtil::ToStr( v, buf, BUF_SIZE );
  1508. PushAttribute( name, buf );
  1509. }
  1510. void XMLPrinter::CloseElement()
  1511. {
  1512. --depth;
  1513. const char* name = stack.Pop();
  1514. if ( elementJustOpened ) {
  1515. Print( "/>" );
  1516. }
  1517. else {
  1518. if ( textDepth < 0 && !compactMode) {
  1519. Print( "\n" );
  1520. PrintSpace( depth );
  1521. }
  1522. Print( "</%s>", name );
  1523. }
  1524. if ( textDepth == depth )
  1525. textDepth = -1;
  1526. if ( depth == 0 && !compactMode)
  1527. Print( "\n" );
  1528. elementJustOpened = false;
  1529. }
  1530. void XMLPrinter::SealElement()
  1531. {
  1532. elementJustOpened = false;
  1533. Print( ">" );
  1534. }
  1535. void XMLPrinter::PushText( const char* text, bool cdata )
  1536. {
  1537. textDepth = depth-1;
  1538. if ( elementJustOpened ) {
  1539. SealElement();
  1540. }
  1541. if ( cdata ) {
  1542. Print( "<![CDATA[" );
  1543. Print( "%s", text );
  1544. Print( "]]>" );
  1545. }
  1546. else {
  1547. PrintString( text, true );
  1548. }
  1549. }
  1550. void XMLPrinter::PushText( int value )
  1551. {
  1552. char buf[BUF_SIZE];
  1553. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1554. PushText( buf, false );
  1555. }
  1556. void XMLPrinter::PushText( unsigned value )
  1557. {
  1558. char buf[BUF_SIZE];
  1559. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1560. PushText( buf, false );
  1561. }
  1562. void XMLPrinter::PushText( bool value )
  1563. {
  1564. char buf[BUF_SIZE];
  1565. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1566. PushText( buf, false );
  1567. }
  1568. void XMLPrinter::PushText( float value )
  1569. {
  1570. char buf[BUF_SIZE];
  1571. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1572. PushText( buf, false );
  1573. }
  1574. void XMLPrinter::PushText( double value )
  1575. {
  1576. char buf[BUF_SIZE];
  1577. XMLUtil::ToStr( value, buf, BUF_SIZE );
  1578. PushText( buf, false );
  1579. }
  1580. void XMLPrinter::PushComment( const char* comment )
  1581. {
  1582. if ( elementJustOpened ) {
  1583. SealElement();
  1584. }
  1585. if ( textDepth < 0 && !firstElement && !compactMode) {
  1586. Print( "\n" );
  1587. PrintSpace( depth );
  1588. }
  1589. firstElement = false;
  1590. Print( "<!--%s-->", comment );
  1591. }
  1592. void XMLPrinter::PushDeclaration( const char* value )
  1593. {
  1594. if ( elementJustOpened ) {
  1595. SealElement();
  1596. }
  1597. if ( textDepth < 0 && !firstElement && !compactMode) {
  1598. Print( "\n" );
  1599. PrintSpace( depth );
  1600. }
  1601. firstElement = false;
  1602. Print( "<?%s?>", value );
  1603. }
  1604. void XMLPrinter::PushUnknown( const char* value )
  1605. {
  1606. if ( elementJustOpened ) {
  1607. SealElement();
  1608. }
  1609. if ( textDepth < 0 && !firstElement && !compactMode) {
  1610. Print( "\n" );
  1611. PrintSpace( depth );
  1612. }
  1613. firstElement = false;
  1614. Print( "<!%s>", value );
  1615. }
  1616. bool XMLPrinter::VisitEnter( const XMLDocument& doc )
  1617. {
  1618. processEntities = doc.ProcessEntities();
  1619. if ( doc.HasBOM() ) {
  1620. PushHeader( true, false );
  1621. }
  1622. return true;
  1623. }
  1624. bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute )
  1625. {
  1626. OpenElement( element.Name() );
  1627. while ( attribute ) {
  1628. PushAttribute( attribute->Name(), attribute->Value() );
  1629. attribute = attribute->Next();
  1630. }
  1631. return true;
  1632. }
  1633. bool XMLPrinter::VisitExit( const XMLElement& )
  1634. {
  1635. CloseElement();
  1636. return true;
  1637. }
  1638. bool XMLPrinter::Visit( const XMLText& text )
  1639. {
  1640. PushText( text.Value(), text.CData() );
  1641. return true;
  1642. }
  1643. bool XMLPrinter::Visit( const XMLComment& comment )
  1644. {
  1645. PushComment( comment.Value() );
  1646. return true;
  1647. }
  1648. bool XMLPrinter::Visit( const XMLDeclaration& declaration )
  1649. {
  1650. PushDeclaration( declaration.Value() );
  1651. return true;
  1652. }
  1653. bool XMLPrinter::Visit( const XMLUnknown& unknown )
  1654. {
  1655. PushUnknown( unknown.Value() );
  1656. return true;
  1657. }