tinyxml2.cpp 43 KB

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