1
0

tinyxml2.cpp 39 KB

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