tinyxml2.cpp 30 KB

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