1
0

tinyxml2.cpp 39 KB

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