tinyxml2.cpp 38 KB

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