tinyxml2.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  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. // FIXME: is it the correct closing element?
  496. if ( node->IsClosingElement() ) {
  497. DELETE_NODE( node );
  498. return p;
  499. }
  500. this->InsertEndChild( node );
  501. }
  502. }
  503. return 0;
  504. }
  505. // --------- XMLText ---------- //
  506. char* XMLText::ParseDeep( char* p )
  507. {
  508. const char* start = p;
  509. if ( this->CData() ) {
  510. p = value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION );
  511. if ( !p ) {
  512. document->SetError( ERROR_PARSING_CDATA, start, 0 );
  513. }
  514. return p;
  515. }
  516. else {
  517. p = value.ParseText( p, "<", StrPair::TEXT_ELEMENT );
  518. if ( !p ) {
  519. document->SetError( ERROR_PARSING_TEXT, start, 0 );
  520. }
  521. if ( p && *p ) {
  522. return p-1;
  523. }
  524. }
  525. return 0;
  526. }
  527. bool XMLText::Accept( XMLVisitor* visitor ) const
  528. {
  529. return visitor->Visit( *this );
  530. }
  531. // --------- XMLComment ---------- //
  532. XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc )
  533. {
  534. }
  535. XMLComment::~XMLComment()
  536. {
  537. //printf( "~XMLComment\n" );
  538. }
  539. char* XMLComment::ParseDeep( char* p )
  540. {
  541. // Comment parses as text.
  542. const char* start = p;
  543. p = value.ParseText( p, "-->", StrPair::COMMENT );
  544. if ( p == 0 ) {
  545. document->SetError( ERROR_PARSING_COMMENT, start, 0 );
  546. }
  547. return p;
  548. }
  549. bool XMLComment::Accept( XMLVisitor* visitor ) const
  550. {
  551. return visitor->Visit( *this );
  552. }
  553. // --------- XMLDeclaration ---------- //
  554. XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc )
  555. {
  556. }
  557. XMLDeclaration::~XMLDeclaration()
  558. {
  559. //printf( "~XMLDeclaration\n" );
  560. }
  561. char* XMLDeclaration::ParseDeep( char* p )
  562. {
  563. // Declaration parses as text.
  564. const char* start = p;
  565. p = value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION );
  566. if ( p == 0 ) {
  567. document->SetError( ERROR_PARSING_DECLARATION, start, 0 );
  568. }
  569. return p;
  570. }
  571. bool XMLDeclaration::Accept( XMLVisitor* visitor ) const
  572. {
  573. return visitor->Visit( *this );
  574. }
  575. // --------- XMLUnknown ---------- //
  576. XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc )
  577. {
  578. }
  579. XMLUnknown::~XMLUnknown()
  580. {
  581. }
  582. char* XMLUnknown::ParseDeep( char* p )
  583. {
  584. // Unknown parses as text.
  585. const char* start = p;
  586. p = value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION );
  587. if ( !p ) {
  588. document->SetError( ERROR_PARSING_UNKNOWN, start, 0 );
  589. }
  590. return p;
  591. }
  592. bool XMLUnknown::Accept( XMLVisitor* visitor ) const
  593. {
  594. return visitor->Visit( *this );
  595. }
  596. // --------- XMLAttribute ---------- //
  597. char* XMLAttribute::ParseDeep( char* p )
  598. {
  599. p = name.ParseText( p, "=", StrPair::ATTRIBUTE_NAME );
  600. if ( !p || !*p ) return 0;
  601. char endTag[2] = { *p, 0 };
  602. ++p;
  603. p = value.ParseText( p, endTag, StrPair::ATTRIBUTE_VALUE );
  604. if ( value.Empty() ) return 0;
  605. return p;
  606. }
  607. void XMLAttribute::SetName( const char* n )
  608. {
  609. name.SetStr( n );
  610. }
  611. int XMLAttribute::QueryIntAttribute( int* value ) const
  612. {
  613. if ( TIXML_SSCANF( Value(), "%d", value ) == 1 )
  614. return XML_NO_ERROR;
  615. return WRONG_ATTRIBUTE_TYPE;
  616. }
  617. int XMLAttribute::QueryUnsignedAttribute( unsigned int* value ) const
  618. {
  619. if ( TIXML_SSCANF( Value(), "%u", value ) == 1 )
  620. return XML_NO_ERROR;
  621. return WRONG_ATTRIBUTE_TYPE;
  622. }
  623. int XMLAttribute::QueryBoolAttribute( bool* value ) const
  624. {
  625. int ival = -1;
  626. QueryIntAttribute( &ival );
  627. if ( ival > 0 || XMLUtil::StringEqual( Value(), "true" ) ) {
  628. *value = true;
  629. return XML_NO_ERROR;
  630. }
  631. else if ( ival == 0 || XMLUtil::StringEqual( Value(), "false" ) ) {
  632. *value = false;
  633. return XML_NO_ERROR;
  634. }
  635. return WRONG_ATTRIBUTE_TYPE;
  636. }
  637. int XMLAttribute::QueryDoubleAttribute( double* value ) const
  638. {
  639. if ( TIXML_SSCANF( Value(), "%lf", value ) == 1 )
  640. return XML_NO_ERROR;
  641. return WRONG_ATTRIBUTE_TYPE;
  642. }
  643. int XMLAttribute::QueryFloatAttribute( float* value ) const
  644. {
  645. if ( TIXML_SSCANF( Value(), "%f", value ) == 1 )
  646. return XML_NO_ERROR;
  647. return WRONG_ATTRIBUTE_TYPE;
  648. }
  649. void XMLAttribute::SetAttribute( const char* v )
  650. {
  651. value.SetStr( v );
  652. }
  653. void XMLAttribute::SetAttribute( int v )
  654. {
  655. char buf[BUF_SIZE];
  656. TIXML_SNPRINTF( buf, BUF_SIZE-1, "%d", v );
  657. value.SetStr( buf );
  658. }
  659. void XMLAttribute::SetAttribute( unsigned v )
  660. {
  661. char buf[BUF_SIZE];
  662. TIXML_SNPRINTF( buf, BUF_SIZE-1, "%u", v );
  663. value.SetStr( buf );
  664. }
  665. void XMLAttribute::SetAttribute( bool v )
  666. {
  667. char buf[BUF_SIZE];
  668. TIXML_SNPRINTF( buf, BUF_SIZE-1, "%d", v ? 1 : 0 );
  669. value.SetStr( buf );
  670. }
  671. void XMLAttribute::SetAttribute( double v )
  672. {
  673. char buf[BUF_SIZE];
  674. TIXML_SNPRINTF( buf, BUF_SIZE-1, "%f", v );
  675. value.SetStr( buf );
  676. }
  677. void XMLAttribute::SetAttribute( float v )
  678. {
  679. char buf[BUF_SIZE];
  680. TIXML_SNPRINTF( buf, BUF_SIZE-1, "%f", v );
  681. value.SetStr( buf );
  682. }
  683. // --------- XMLElement ---------- //
  684. XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ),
  685. closing( false ),
  686. rootAttribute( 0 )
  687. //lastAttribute( 0 )
  688. {
  689. }
  690. XMLElement::~XMLElement()
  691. {
  692. while( rootAttribute ) {
  693. XMLAttribute* next = rootAttribute->next;
  694. DELETE_ATTRIBUTE( rootAttribute );
  695. rootAttribute = next;
  696. }
  697. }
  698. XMLAttribute* XMLElement::FindAttribute( const char* name )
  699. {
  700. XMLAttribute* a = 0;
  701. for( a=rootAttribute; a; a = a->next ) {
  702. if ( XMLUtil::StringEqual( a->Name(), name ) )
  703. return a;
  704. }
  705. return 0;
  706. }
  707. const XMLAttribute* XMLElement::FindAttribute( const char* name ) const
  708. {
  709. XMLAttribute* a = 0;
  710. for( a=rootAttribute; a; a = a->next ) {
  711. if ( XMLUtil::StringEqual( a->Name(), name ) )
  712. return a;
  713. }
  714. return 0;
  715. }
  716. const char* XMLElement::GetText() const
  717. {
  718. if ( FirstChild() && FirstChild()->ToText() ) {
  719. return FirstChild()->ToText()->Value();
  720. }
  721. return 0;
  722. }
  723. XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name )
  724. {
  725. XMLAttribute* attrib = FindAttribute( name );
  726. if ( !attrib ) {
  727. attrib = new (document->attributePool.Alloc() ) XMLAttribute( this );
  728. attrib->memPool = &document->attributePool;
  729. LinkAttribute( attrib );
  730. attrib->SetName( name );
  731. }
  732. return attrib;
  733. }
  734. void XMLElement::LinkAttribute( XMLAttribute* attrib )
  735. {
  736. if ( rootAttribute ) {
  737. XMLAttribute* end = rootAttribute;
  738. while ( end->next )
  739. end = end->next;
  740. end->next = attrib;
  741. }
  742. else {
  743. rootAttribute = attrib;
  744. }
  745. }
  746. void XMLElement::DeleteAttribute( const char* name )
  747. {
  748. XMLAttribute* prev = 0;
  749. for( XMLAttribute* a=rootAttribute; a; a=a->next ) {
  750. if ( XMLUtil::StringEqual( name, a->Name() ) ) {
  751. if ( prev ) {
  752. prev->next = a->next;
  753. }
  754. else {
  755. rootAttribute = a->next;
  756. }
  757. DELETE_ATTRIBUTE( a );
  758. break;
  759. }
  760. prev = a;
  761. }
  762. }
  763. char* XMLElement::ParseAttributes( char* p, bool* closedElement )
  764. {
  765. const char* start = p;
  766. *closedElement = false;
  767. // Read the attributes.
  768. while( p ) {
  769. p = XMLUtil::SkipWhiteSpace( p );
  770. if ( !p || !(*p) ) {
  771. document->SetError( ERROR_PARSING_ELEMENT, start, Name() );
  772. return 0;
  773. }
  774. // attribute.
  775. if ( XMLUtil::IsAlpha( *p ) ) {
  776. XMLAttribute* attrib = new (document->attributePool.Alloc() ) XMLAttribute( this );
  777. attrib->memPool = &document->attributePool;
  778. p = attrib->ParseDeep( p );
  779. if ( !p ) {
  780. DELETE_ATTRIBUTE( attrib );
  781. document->SetError( ERROR_PARSING_ATTRIBUTE, start, p );
  782. return 0;
  783. }
  784. LinkAttribute( attrib );
  785. }
  786. // end of the tag
  787. else if ( *p == '/' && *(p+1) == '>' ) {
  788. if ( closing ) {
  789. document->SetError( ERROR_PARSING_ELEMENT, start, p );
  790. return 0;
  791. }
  792. *closedElement = true;
  793. return p+2; // done; sealed element.
  794. }
  795. // end of the tag
  796. else if ( *p == '>' ) {
  797. ++p;
  798. break;
  799. }
  800. else {
  801. document->SetError( ERROR_PARSING_ELEMENT, start, p );
  802. return 0;
  803. }
  804. }
  805. return p;
  806. }
  807. //
  808. // <ele></ele>
  809. // <ele>foo<b>bar</b></ele>
  810. //
  811. char* XMLElement::ParseDeep( char* p )
  812. {
  813. // Read the element name.
  814. p = XMLUtil::SkipWhiteSpace( p );
  815. if ( !p ) return 0;
  816. const char* start = p;
  817. // The closing element is the </element> form. It is
  818. // parsed just like a regular element then deleted from
  819. // the DOM.
  820. if ( *p == '/' ) {
  821. closing = true;
  822. ++p;
  823. }
  824. p = value.ParseName( p );
  825. if ( value.Empty() ) return 0;
  826. bool elementClosed=false;
  827. p = ParseAttributes( p, &elementClosed );
  828. if ( !p || !*p || elementClosed || closing )
  829. return p;
  830. p = XMLNode::ParseDeep( p );
  831. return p;
  832. }
  833. bool XMLElement::Accept( XMLVisitor* visitor ) const
  834. {
  835. if ( visitor->VisitEnter( *this, rootAttribute ) )
  836. {
  837. for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() )
  838. {
  839. if ( !node->Accept( visitor ) )
  840. break;
  841. }
  842. }
  843. return visitor->VisitExit( *this );
  844. }
  845. // --------- XMLDocument ----------- //
  846. XMLDocument::XMLDocument() :
  847. XMLNode( 0 ),
  848. writeBOM( false ),
  849. charBuffer( 0 )
  850. {
  851. document = this; // avoid warning about 'this' in initializer list
  852. }
  853. XMLDocument::~XMLDocument()
  854. {
  855. ClearChildren();
  856. delete [] charBuffer;
  857. #if 0
  858. textPool.Trace( "text" );
  859. elementPool.Trace( "element" );
  860. commentPool.Trace( "comment" );
  861. attributePool.Trace( "attribute" );
  862. #endif
  863. TIXMLASSERT( textPool.CurrentAllocs() == 0 );
  864. TIXMLASSERT( elementPool.CurrentAllocs() == 0 );
  865. TIXMLASSERT( commentPool.CurrentAllocs() == 0 );
  866. TIXMLASSERT( attributePool.CurrentAllocs() == 0 );
  867. }
  868. void XMLDocument::InitDocument()
  869. {
  870. errorID = XML_NO_ERROR;
  871. errorStr1 = 0;
  872. errorStr2 = 0;
  873. delete [] charBuffer;
  874. charBuffer = 0;
  875. }
  876. XMLElement* XMLDocument::NewElement( const char* name )
  877. {
  878. XMLElement* ele = new (elementPool.Alloc()) XMLElement( this );
  879. ele->memPool = &elementPool;
  880. ele->SetName( name );
  881. return ele;
  882. }
  883. XMLComment* XMLDocument::NewComment( const char* str )
  884. {
  885. XMLComment* comment = new (commentPool.Alloc()) XMLComment( this );
  886. comment->memPool = &commentPool;
  887. comment->SetValue( str );
  888. return comment;
  889. }
  890. XMLText* XMLDocument::NewText( const char* str )
  891. {
  892. XMLText* text = new (textPool.Alloc()) XMLText( this );
  893. text->memPool = &textPool;
  894. text->SetValue( str );
  895. return text;
  896. }
  897. int XMLDocument::LoadFile( const char* filename )
  898. {
  899. ClearChildren();
  900. InitDocument();
  901. FILE* fp = fopen( filename, "rb" );
  902. if ( !fp ) {
  903. SetError( ERROR_FILE_NOT_FOUND, filename, 0 );
  904. return errorID;
  905. }
  906. LoadFile( fp );
  907. fclose( fp );
  908. return errorID;
  909. }
  910. int XMLDocument::LoadFile( FILE* fp )
  911. {
  912. ClearChildren();
  913. InitDocument();
  914. fseek( fp, 0, SEEK_END );
  915. unsigned size = ftell( fp );
  916. fseek( fp, 0, SEEK_SET );
  917. if ( size == 0 ) {
  918. return errorID;
  919. }
  920. charBuffer = new char[size+1];
  921. fread( charBuffer, size, 1, fp );
  922. charBuffer[size] = 0;
  923. const char* p = charBuffer;
  924. p = XMLUtil::SkipWhiteSpace( p );
  925. p = XMLUtil::ReadBOM( p, &writeBOM );
  926. if ( !p || !*p ) {
  927. return 0; // correctly parse an empty string?
  928. }
  929. ParseDeep( charBuffer + (p-charBuffer) );
  930. return errorID;
  931. }
  932. void XMLDocument::SaveFile( const char* filename )
  933. {
  934. FILE* fp = fopen( filename, "w" );
  935. XMLStreamer stream( fp );
  936. Print( &stream );
  937. fclose( fp );
  938. }
  939. int XMLDocument::Parse( const char* p )
  940. {
  941. ClearChildren();
  942. InitDocument();
  943. if ( !p || !*p ) {
  944. return true; // correctly parse an empty string?
  945. }
  946. p = XMLUtil::SkipWhiteSpace( p );
  947. p = XMLUtil::ReadBOM( p, &writeBOM );
  948. if ( !p || !*p ) {
  949. return true; // correctly parse an empty string?
  950. }
  951. size_t len = strlen( p );
  952. charBuffer = new char[ len+1 ];
  953. memcpy( charBuffer, p, len+1 );
  954. ParseDeep( charBuffer );
  955. return errorID;
  956. }
  957. void XMLDocument::Print( XMLStreamer* streamer )
  958. {
  959. XMLStreamer stdStreamer( stdout );
  960. if ( !streamer )
  961. streamer = &stdStreamer;
  962. //for( XMLNode* node = firstChild; node; node=node->next ) {
  963. // node->Print( streamer );
  964. //}
  965. Accept( streamer );
  966. }
  967. void XMLDocument::SetError( int error, const char* str1, const char* str2 )
  968. {
  969. errorID = error;
  970. errorStr1 = str1;
  971. errorStr2 = str2;
  972. }
  973. void XMLDocument::PrintError() const
  974. {
  975. if ( errorID ) {
  976. char buf1[20] = { 0 };
  977. char buf2[20] = { 0 };
  978. if ( errorStr1 ) {
  979. strncpy( buf1, errorStr1, 20 );
  980. buf1[19] = 0;
  981. }
  982. if ( errorStr2 ) {
  983. strncpy( buf2, errorStr2, 20 );
  984. buf2[19] = 0;
  985. }
  986. printf( "XMLDocument error id=%d str1=%s str2=%s\n",
  987. errorID, buf1, buf2 );
  988. }
  989. }
  990. XMLStreamer::XMLStreamer( FILE* file ) :
  991. elementJustOpened( false ),
  992. firstElement( true ),
  993. fp( file ),
  994. depth( 0 ),
  995. textDepth( -1 )
  996. {
  997. for( int i=0; i<ENTITY_RANGE; ++i ) {
  998. entityFlag[i] = false;
  999. restrictedEntityFlag[i] = false;
  1000. }
  1001. for( int i=0; i<NUM_ENTITIES; ++i ) {
  1002. TIXMLASSERT( entities[i].value < ENTITY_RANGE );
  1003. if ( entities[i].value < ENTITY_RANGE ) {
  1004. entityFlag[ entities[i].value ] = true;
  1005. }
  1006. }
  1007. restrictedEntityFlag['&'] = true;
  1008. restrictedEntityFlag['<'] = true;
  1009. restrictedEntityFlag['>'] = true; // not required, but consistency is nice
  1010. buffer.Push( 0 );
  1011. }
  1012. void XMLStreamer::Print( const char* format, ... )
  1013. {
  1014. va_list va;
  1015. va_start( va, format );
  1016. if ( fp ) {
  1017. vfprintf( fp, format, va );
  1018. }
  1019. else {
  1020. // This seems brutally complex. Haven't figured out a better
  1021. // way on windows.
  1022. #ifdef _MSC_VER
  1023. int len = -1;
  1024. int expand = 1000;
  1025. while ( len < 0 ) {
  1026. len = vsnprintf_s( accumulator.Mem(), accumulator.Capacity(), accumulator.Capacity()-1, format, va );
  1027. if ( len < 0 ) {
  1028. accumulator.PushArr( expand );
  1029. expand *= 3/2;
  1030. }
  1031. }
  1032. char* p = buffer.PushArr( len ) - 1;
  1033. memcpy( p, accumulator.Mem(), len+1 );
  1034. #else
  1035. int len = vsnprintf( 0, 0, format, va );
  1036. char* p = buffer.PushArr( len ) - 1;
  1037. vsprintf_s( p, len+1, format, va );
  1038. #endif
  1039. }
  1040. va_end( va );
  1041. }
  1042. void XMLStreamer::PrintSpace( int depth )
  1043. {
  1044. for( int i=0; i<depth; ++i ) {
  1045. Print( " " );
  1046. }
  1047. }
  1048. void XMLStreamer::PrintString( const char* p, bool restricted )
  1049. {
  1050. // Look for runs of bytes between entities to print.
  1051. const char* q = p;
  1052. const bool* flag = restricted ? restrictedEntityFlag : entityFlag;
  1053. while ( *q ) {
  1054. // Remember, char is sometimes signed. (How many times has that bitten me?)
  1055. if ( *q > 0 && *q < ENTITY_RANGE ) {
  1056. // Check for entities. If one is found, flush
  1057. // the stream up until the entity, write the
  1058. // entity, and keep looking.
  1059. if ( flag[*q] ) {
  1060. while ( p < q ) {
  1061. Print( "%c", *p );
  1062. ++p;
  1063. }
  1064. for( int i=0; i<NUM_ENTITIES; ++i ) {
  1065. if ( entities[i].value == *q ) {
  1066. Print( "&%s;", entities[i].pattern );
  1067. break;
  1068. }
  1069. }
  1070. ++p;
  1071. }
  1072. }
  1073. ++q;
  1074. }
  1075. // Flush the remaining string. This will be the entire
  1076. // string if an entity wasn't found.
  1077. if ( q-p > 0 ) {
  1078. Print( "%s", p );
  1079. }
  1080. }
  1081. void XMLStreamer::PushHeader( bool writeBOM, bool writeDec )
  1082. {
  1083. static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 };
  1084. if ( writeBOM ) {
  1085. Print( "%s", bom );
  1086. }
  1087. if ( writeDec ) {
  1088. PushDeclaration( "xml version=\"1.0\"" );
  1089. }
  1090. }
  1091. void XMLStreamer::OpenElement( const char* name )
  1092. {
  1093. if ( elementJustOpened ) {
  1094. SealElement();
  1095. }
  1096. stack.Push( name );
  1097. if ( textDepth < 0 && !firstElement ) {
  1098. Print( "\n" );
  1099. PrintSpace( depth );
  1100. }
  1101. Print( "<%s", name );
  1102. elementJustOpened = true;
  1103. firstElement = false;
  1104. ++depth;
  1105. }
  1106. void XMLStreamer::PushAttribute( const char* name, const char* value )
  1107. {
  1108. TIXMLASSERT( elementJustOpened );
  1109. Print( " %s=\"", name );
  1110. PrintString( value, false );
  1111. Print( "\"" );
  1112. }
  1113. void XMLStreamer::CloseElement()
  1114. {
  1115. --depth;
  1116. const char* name = stack.Pop();
  1117. if ( elementJustOpened ) {
  1118. Print( "/>" );
  1119. }
  1120. else {
  1121. if ( textDepth < 0 ) {
  1122. Print( "\n" );
  1123. PrintSpace( depth );
  1124. }
  1125. Print( "</%s>", name );
  1126. }
  1127. if ( textDepth == depth )
  1128. textDepth = -1;
  1129. if ( depth == 0 )
  1130. Print( "\n" );
  1131. elementJustOpened = false;
  1132. }
  1133. void XMLStreamer::SealElement()
  1134. {
  1135. elementJustOpened = false;
  1136. Print( ">" );
  1137. }
  1138. void XMLStreamer::PushText( const char* text, bool cdata )
  1139. {
  1140. textDepth = depth-1;
  1141. if ( elementJustOpened ) {
  1142. SealElement();
  1143. }
  1144. if ( cdata ) {
  1145. Print( "<![CDATA[" );
  1146. Print( "%s", text );
  1147. Print( "]]>" );
  1148. }
  1149. else {
  1150. PrintString( text, true );
  1151. }
  1152. }
  1153. void XMLStreamer::PushComment( const char* comment )
  1154. {
  1155. if ( elementJustOpened ) {
  1156. SealElement();
  1157. }
  1158. if ( textDepth < 0 && !firstElement ) {
  1159. Print( "\n" );
  1160. PrintSpace( depth );
  1161. }
  1162. firstElement = false;
  1163. Print( "<!--%s-->", comment );
  1164. }
  1165. void XMLStreamer::PushDeclaration( const char* value )
  1166. {
  1167. if ( elementJustOpened ) {
  1168. SealElement();
  1169. }
  1170. if ( textDepth < 0 && !firstElement) {
  1171. Print( "\n" );
  1172. PrintSpace( depth );
  1173. }
  1174. firstElement = false;
  1175. Print( "<?%s?>", value );
  1176. }
  1177. void XMLStreamer::PushUnknown( const char* value )
  1178. {
  1179. if ( elementJustOpened ) {
  1180. SealElement();
  1181. }
  1182. if ( textDepth < 0 && !firstElement ) {
  1183. Print( "\n" );
  1184. PrintSpace( depth );
  1185. }
  1186. firstElement = false;
  1187. Print( "<!%s>", value );
  1188. }
  1189. bool XMLStreamer::VisitEnter( const XMLDocument& doc )
  1190. {
  1191. if ( doc.HasBOM() ) {
  1192. PushHeader( true, false );
  1193. }
  1194. return true;
  1195. }
  1196. bool XMLStreamer::VisitEnter( const XMLElement& element, const XMLAttribute* attribute )
  1197. {
  1198. OpenElement( element.Name() );
  1199. while ( attribute ) {
  1200. PushAttribute( attribute->Name(), attribute->Value() );
  1201. attribute = attribute->Next();
  1202. }
  1203. return true;
  1204. }
  1205. bool XMLStreamer::VisitExit( const XMLElement& element )
  1206. {
  1207. CloseElement();
  1208. return true;
  1209. }
  1210. bool XMLStreamer::Visit( const XMLText& text )
  1211. {
  1212. PushText( text.Value() );
  1213. return true;
  1214. }
  1215. bool XMLStreamer::Visit( const XMLComment& comment )
  1216. {
  1217. PushComment( comment.Value() );
  1218. return true;
  1219. }
  1220. bool XMLStreamer::Visit( const XMLDeclaration& declaration )
  1221. {
  1222. PushDeclaration( declaration.Value() );
  1223. return true;
  1224. }
  1225. bool XMLStreamer::Visit( const XMLUnknown& unknown )
  1226. {
  1227. PushUnknown( unknown.Value() );
  1228. return true;
  1229. }