xmltest.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. #include "tinyxml2.h"
  2. #include <cstdlib>
  3. #include <cstring>
  4. #include <ctime>
  5. #if defined( _MSC_VER )
  6. #include <direct.h> // _mkdir
  7. #include <crtdbg.h>
  8. #define WIN32_LEAN_AND_MEAN
  9. #include <windows.h>
  10. _CrtMemState startMemState;
  11. _CrtMemState endMemState;
  12. #else
  13. #include <sys/stat.h> // mkdir
  14. #endif
  15. using namespace tinyxml2;
  16. int gPass = 0;
  17. int gFail = 0;
  18. bool XMLTest (const char* testString, const char* expected, const char* found, bool echo=true )
  19. {
  20. bool pass = !strcmp( expected, found );
  21. if ( pass )
  22. printf ("[pass]");
  23. else
  24. printf ("[fail]");
  25. if ( !echo )
  26. printf (" %s\n", testString);
  27. else
  28. printf (" %s [%s][%s]\n", testString, expected, found);
  29. if ( pass )
  30. ++gPass;
  31. else
  32. ++gFail;
  33. return pass;
  34. }
  35. template< class T > bool XMLTest( const char* testString, T expected, T found, bool echo=true )
  36. {
  37. bool pass = ( expected == found );
  38. if ( pass )
  39. printf ("[pass]");
  40. else
  41. printf ("[fail]");
  42. if ( !echo )
  43. printf (" %s\n", testString);
  44. else
  45. printf (" %s [%d][%d]\n", testString, static_cast<int>(expected), static_cast<int>(found) );
  46. if ( pass )
  47. ++gPass;
  48. else
  49. ++gFail;
  50. return pass;
  51. }
  52. void NullLineEndings( char* p )
  53. {
  54. while( p && *p ) {
  55. if ( *p == '\n' || *p == '\r' ) {
  56. *p = 0;
  57. return;
  58. }
  59. ++p;
  60. }
  61. }
  62. // Comments in the header. (Don't know how to get Doxygen to read comments in this file.)
  63. int example_1()
  64. {
  65. XMLDocument doc;
  66. doc.LoadFile( "resources/dream.xml" );
  67. return doc.ErrorID();
  68. }
  69. // Comments in the header. (Don't know how to get Doxygen to read comments in this file.)
  70. int example_2()
  71. {
  72. static const char* xml = "<element/>";
  73. XMLDocument doc;
  74. doc.Parse( xml );
  75. return doc.ErrorID();
  76. }
  77. int example_3()
  78. {
  79. static const char* xml =
  80. "<?xml version=\"1.0\"?>"
  81. "<!DOCTYPE PLAY SYSTEM \"play.dtd\">"
  82. "<PLAY>"
  83. "<TITLE>A Midsummer Night's Dream</TITLE>"
  84. "</PLAY>";
  85. XMLDocument doc;
  86. doc.Parse( xml );
  87. XMLElement* titleElement = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" );
  88. const char* title = titleElement->GetText();
  89. printf( "Name of play (1): %s\n", title );
  90. XMLText* textNode = titleElement->FirstChild()->ToText();
  91. title = textNode->Value();
  92. printf( "Name of play (2): %s\n", title );
  93. return doc.ErrorID();
  94. }
  95. bool example_4()
  96. {
  97. static const char* xml =
  98. "<information>"
  99. " <attributeApproach v='2' />"
  100. " <textApproach>"
  101. " <v>2</v>"
  102. " </textApproach>"
  103. "</information>";
  104. XMLDocument doc;
  105. doc.Parse( xml );
  106. int v0 = 0;
  107. int v1 = 0;
  108. XMLElement* attributeApproachElement = doc.FirstChildElement()->FirstChildElement( "attributeApproach" );
  109. attributeApproachElement->QueryIntAttribute( "v", &v0 );
  110. XMLElement* textApproachElement = doc.FirstChildElement()->FirstChildElement( "textApproach" );
  111. textApproachElement->FirstChildElement( "v" )->QueryIntText( &v1 );
  112. printf( "Both values are the same: %d and %d\n", v0, v1 );
  113. return !doc.Error() && ( v0 == v1 );
  114. }
  115. int main( int /*argc*/, const char ** /*argv*/ )
  116. {
  117. #if defined( _MSC_VER ) && defined( DEBUG )
  118. _CrtMemCheckpoint( &startMemState );
  119. #endif
  120. #if defined(_MSC_VER)
  121. _mkdir( "resources/out/" );
  122. #else
  123. mkdir( "resources/out/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  124. #endif
  125. FILE* fp = fopen( "resources/dream.xml", "r" );
  126. if ( !fp ) {
  127. printf( "Error opening test file 'dream.xml'.\n"
  128. "Is your working directory the same as where \n"
  129. "the xmltest.cpp and dream.xml file are?\n\n"
  130. #if defined( _MSC_VER )
  131. "In windows Visual Studio you may need to set\n"
  132. "Properties->Debugging->Working Directory to '..'\n"
  133. #endif
  134. );
  135. exit( 1 );
  136. }
  137. fclose( fp );
  138. XMLTest( "Example-1", 0, example_1() );
  139. XMLTest( "Example-2", 0, example_2() );
  140. XMLTest( "Example-3", 0, example_3() );
  141. XMLTest( "Example-4", true, example_4() );
  142. /* ------ Example 2: Lookup information. ---- */
  143. {
  144. static const char* test[] = { "<element />",
  145. "<element></element>",
  146. "<element><subelement/></element>",
  147. "<element><subelement></subelement></element>",
  148. "<element><subelement><subsub/></subelement></element>",
  149. "<!--comment beside elements--><element><subelement></subelement></element>",
  150. "<!--comment beside elements, this time with spaces--> \n <element> <subelement> \n </subelement> </element>",
  151. "<element attrib1='foo' attrib2=\"bar\" ></element>",
  152. "<element attrib1='foo' attrib2=\"bar\" ><subelement attrib3='yeehaa' /></element>",
  153. "<element>Text inside element.</element>",
  154. "<element><b></b></element>",
  155. "<element>Text inside and <b>bolded</b> in the element.</element>",
  156. "<outer><element>Text inside and <b>bolded</b> in the element.</element></outer>",
  157. "<element>This &amp; That.</element>",
  158. "<element attrib='This&lt;That' />",
  159. 0
  160. };
  161. for( int i=0; test[i]; ++i ) {
  162. XMLDocument doc;
  163. doc.Parse( test[i] );
  164. doc.Print();
  165. printf( "----------------------------------------------\n" );
  166. }
  167. }
  168. #if 1
  169. {
  170. static const char* test = "<!--hello world\n"
  171. " line 2\r"
  172. " line 3\r\n"
  173. " line 4\n\r"
  174. " line 5\r-->";
  175. XMLDocument doc;
  176. doc.Parse( test );
  177. doc.Print();
  178. }
  179. {
  180. static const char* test = "<element>Text before.</element>";
  181. XMLDocument doc;
  182. doc.Parse( test );
  183. XMLElement* root = doc.FirstChildElement();
  184. XMLElement* newElement = doc.NewElement( "Subelement" );
  185. root->InsertEndChild( newElement );
  186. doc.Print();
  187. }
  188. {
  189. XMLDocument* doc = new XMLDocument();
  190. static const char* test = "<element><sub/></element>";
  191. doc->Parse( test );
  192. delete doc;
  193. }
  194. {
  195. // Test: Programmatic DOM
  196. // Build:
  197. // <element>
  198. // <!--comment-->
  199. // <sub attrib="1" />
  200. // <sub attrib="2" />
  201. // <sub attrib="3" >& Text!</sub>
  202. // <element>
  203. XMLDocument* doc = new XMLDocument();
  204. XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) );
  205. XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) };
  206. for( int i=0; i<3; ++i ) {
  207. sub[i]->SetAttribute( "attrib", i );
  208. }
  209. element->InsertEndChild( sub[2] );
  210. XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) );
  211. element->InsertAfterChild( comment, sub[0] );
  212. element->InsertAfterChild( sub[0], sub[1] );
  213. sub[2]->InsertFirstChild( doc->NewText( "& Text!" ));
  214. doc->Print();
  215. XMLTest( "Programmatic DOM", "comment", doc->FirstChildElement( "element" )->FirstChild()->Value() );
  216. XMLTest( "Programmatic DOM", "0", doc->FirstChildElement( "element" )->FirstChildElement()->Attribute( "attrib" ) );
  217. XMLTest( "Programmatic DOM", 2, doc->FirstChildElement()->LastChildElement( "sub" )->IntAttribute( "attrib" ) );
  218. XMLTest( "Programmatic DOM", "& Text!",
  219. doc->FirstChildElement()->LastChildElement( "sub" )->FirstChild()->ToText()->Value() );
  220. // And now deletion:
  221. element->DeleteChild( sub[2] );
  222. doc->DeleteNode( comment );
  223. element->FirstChildElement()->SetAttribute( "attrib", true );
  224. element->LastChildElement()->DeleteAttribute( "attrib" );
  225. XMLTest( "Programmatic DOM", true, doc->FirstChildElement()->FirstChildElement()->BoolAttribute( "attrib" ) );
  226. int value = 10;
  227. int result = doc->FirstChildElement()->LastChildElement()->QueryIntAttribute( "attrib", &value );
  228. XMLTest( "Programmatic DOM", result, (int)XML_NO_ATTRIBUTE );
  229. XMLTest( "Programmatic DOM", value, 10 );
  230. doc->Print();
  231. {
  232. XMLPrinter streamer;
  233. doc->Print( &streamer );
  234. printf( "%s", streamer.CStr() );
  235. }
  236. {
  237. XMLPrinter streamer( 0, true );
  238. doc->Print( &streamer );
  239. XMLTest( "Compact mode", "<element><sub attrib=\"1\"/><sub/></element>", streamer.CStr(), false );
  240. }
  241. doc->SaveFile( "./resources/out/pretty.xml" );
  242. doc->SaveFile( "./resources/out/compact.xml", true );
  243. delete doc;
  244. }
  245. {
  246. // Test: Dream
  247. // XML1 : 1,187,569 bytes in 31,209 allocations
  248. // XML2 : 469,073 bytes in 323 allocations
  249. //int newStart = gNew;
  250. XMLDocument doc;
  251. doc.LoadFile( "resources/dream.xml" );
  252. doc.SaveFile( "resources/out/dreamout.xml" );
  253. doc.PrintError();
  254. XMLTest( "Dream", "xml version=\"1.0\"",
  255. doc.FirstChild()->ToDeclaration()->Value() );
  256. XMLTest( "Dream", true, doc.FirstChild()->NextSibling()->ToUnknown() ? true : false );
  257. XMLTest( "Dream", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
  258. doc.FirstChild()->NextSibling()->ToUnknown()->Value() );
  259. XMLTest( "Dream", "And Robin shall restore amends.",
  260. doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
  261. XMLTest( "Dream", "And Robin shall restore amends.",
  262. doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
  263. XMLDocument doc2;
  264. doc2.LoadFile( "resources/out/dreamout.xml" );
  265. XMLTest( "Dream-out", "xml version=\"1.0\"",
  266. doc2.FirstChild()->ToDeclaration()->Value() );
  267. XMLTest( "Dream-out", true, doc2.FirstChild()->NextSibling()->ToUnknown() ? true : false );
  268. XMLTest( "Dream-out", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
  269. doc2.FirstChild()->NextSibling()->ToUnknown()->Value() );
  270. XMLTest( "Dream-out", "And Robin shall restore amends.",
  271. doc2.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
  272. //gNewTotal = gNew - newStart;
  273. }
  274. {
  275. const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n"
  276. "<passages count=\"006\" formatversion=\"20020620\">\n"
  277. " <wrong error>\n"
  278. "</passages>";
  279. XMLDocument doc;
  280. doc.Parse( error );
  281. XMLTest( "Bad XML", doc.ErrorID(), (int)XML_ERROR_PARSING_ATTRIBUTE );
  282. }
  283. {
  284. const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";
  285. XMLDocument doc;
  286. doc.Parse( str );
  287. XMLElement* ele = doc.FirstChildElement();
  288. int iVal, result;
  289. double dVal;
  290. result = ele->QueryDoubleAttribute( "attr0", &dVal );
  291. XMLTest( "Query attribute: int as double", result, (int)XML_NO_ERROR );
  292. XMLTest( "Query attribute: int as double", (int)dVal, 1 );
  293. result = ele->QueryDoubleAttribute( "attr1", &dVal );
  294. XMLTest( "Query attribute: double as double", (int)dVal, 2 );
  295. result = ele->QueryIntAttribute( "attr1", &iVal );
  296. XMLTest( "Query attribute: double as int", result, (int)XML_NO_ERROR );
  297. XMLTest( "Query attribute: double as int", iVal, 2 );
  298. result = ele->QueryIntAttribute( "attr2", &iVal );
  299. XMLTest( "Query attribute: not a number", result, (int)XML_WRONG_ATTRIBUTE_TYPE );
  300. result = ele->QueryIntAttribute( "bar", &iVal );
  301. XMLTest( "Query attribute: does not exist", result, (int)XML_NO_ATTRIBUTE );
  302. }
  303. {
  304. const char* str = "<doc/>";
  305. XMLDocument doc;
  306. doc.Parse( str );
  307. XMLElement* ele = doc.FirstChildElement();
  308. int iVal;
  309. double dVal;
  310. ele->SetAttribute( "str", "strValue" );
  311. ele->SetAttribute( "int", 1 );
  312. ele->SetAttribute( "double", -1.0 );
  313. const char* cStr = ele->Attribute( "str" );
  314. ele->QueryIntAttribute( "int", &iVal );
  315. ele->QueryDoubleAttribute( "double", &dVal );
  316. XMLTest( "Attribute match test", ele->Attribute( "str", "strValue" ), "strValue" );
  317. XMLTest( "Attribute round trip. c-string.", "strValue", cStr );
  318. XMLTest( "Attribute round trip. int.", 1, iVal );
  319. XMLTest( "Attribute round trip. double.", -1, (int)dVal );
  320. }
  321. {
  322. XMLDocument doc;
  323. doc.LoadFile( "resources/utf8test.xml" );
  324. // Get the attribute "value" from the "Russian" element and check it.
  325. XMLElement* element = doc.FirstChildElement( "document" )->FirstChildElement( "Russian" );
  326. const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU,
  327. 0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 };
  328. XMLTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ) );
  329. const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U,
  330. 0xd1U, 0x81U, 0xd1U, 0x81U,
  331. 0xd0U, 0xbaU, 0xd0U, 0xb8U,
  332. 0xd0U, 0xb9U, 0 };
  333. const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";
  334. XMLText* text = doc.FirstChildElement( "document" )->FirstChildElement( (const char*) russianElementName )->FirstChild()->ToText();
  335. XMLTest( "UTF-8: Browsing russian element name.",
  336. russianText,
  337. text->Value() );
  338. // Now try for a round trip.
  339. doc.SaveFile( "resources/out/utf8testout.xml" );
  340. // Check the round trip.
  341. int okay = 0;
  342. FILE* saved = fopen( "resources/out/utf8testout.xml", "r" );
  343. FILE* verify = fopen( "resources/utf8testverify.xml", "r" );
  344. if ( saved && verify )
  345. {
  346. okay = 1;
  347. char verifyBuf[256];
  348. while ( fgets( verifyBuf, 256, verify ) )
  349. {
  350. char savedBuf[256];
  351. fgets( savedBuf, 256, saved );
  352. NullLineEndings( verifyBuf );
  353. NullLineEndings( savedBuf );
  354. if ( strcmp( verifyBuf, savedBuf ) )
  355. {
  356. printf( "verify:%s<\n", verifyBuf );
  357. printf( "saved :%s<\n", savedBuf );
  358. okay = 0;
  359. break;
  360. }
  361. }
  362. }
  363. if ( saved )
  364. fclose( saved );
  365. if ( verify )
  366. fclose( verify );
  367. XMLTest( "UTF-8: Verified multi-language round trip.", 1, okay );
  368. }
  369. // --------GetText()-----------
  370. {
  371. const char* str = "<foo>This is text</foo>";
  372. XMLDocument doc;
  373. doc.Parse( str );
  374. const XMLElement* element = doc.RootElement();
  375. XMLTest( "GetText() normal use.", "This is text", element->GetText() );
  376. str = "<foo><b>This is text</b></foo>";
  377. doc.Parse( str );
  378. element = doc.RootElement();
  379. XMLTest( "GetText() contained element.", element->GetText() == 0, true );
  380. }
  381. // ---------- CDATA ---------------
  382. {
  383. const char* str = "<xmlElement>"
  384. "<![CDATA["
  385. "I am > the rules!\n"
  386. "...since I make symbolic puns"
  387. "]]>"
  388. "</xmlElement>";
  389. XMLDocument doc;
  390. doc.Parse( str );
  391. doc.Print();
  392. XMLTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(),
  393. "I am > the rules!\n...since I make symbolic puns",
  394. false );
  395. }
  396. // ----------- CDATA -------------
  397. {
  398. const char* str = "<xmlElement>"
  399. "<![CDATA["
  400. "<b>I am > the rules!</b>\n"
  401. "...since I make symbolic puns"
  402. "]]>"
  403. "</xmlElement>";
  404. XMLDocument doc;
  405. doc.Parse( str );
  406. doc.Print();
  407. XMLTest( "CDATA parse. [ tixml1:1480107 ]", doc.FirstChildElement()->FirstChild()->Value(),
  408. "<b>I am > the rules!</b>\n...since I make symbolic puns",
  409. false );
  410. }
  411. // InsertAfterChild causes crash.
  412. {
  413. // InsertBeforeChild and InsertAfterChild causes crash.
  414. XMLDocument doc;
  415. XMLElement* parent = doc.NewElement( "Parent" );
  416. doc.InsertFirstChild( parent );
  417. XMLElement* childText0 = doc.NewElement( "childText0" );
  418. XMLElement* childText1 = doc.NewElement( "childText1" );
  419. XMLNode* childNode0 = parent->InsertEndChild( childText0 );
  420. XMLNode* childNode1 = parent->InsertAfterChild( childNode0, childText1 );
  421. XMLTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent->LastChild() ), true );
  422. }
  423. {
  424. // Entities not being written correctly.
  425. // From Lynn Allen
  426. const char* passages =
  427. "<?xml version=\"1.0\" standalone=\"no\" ?>"
  428. "<passages count=\"006\" formatversion=\"20020620\">"
  429. "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
  430. " It also has &lt;, &gt;, and &amp;, as well as a fake copyright &#xA9;.\"> </psg>"
  431. "</passages>";
  432. XMLDocument doc;
  433. doc.Parse( passages );
  434. XMLElement* psg = doc.RootElement()->FirstChildElement();
  435. const char* context = psg->Attribute( "context" );
  436. const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";
  437. XMLTest( "Entity transformation: read. ", expected, context, true );
  438. FILE* textfile = fopen( "resources/out/textfile.txt", "w" );
  439. if ( textfile )
  440. {
  441. XMLPrinter streamer( textfile );
  442. psg->Accept( &streamer );
  443. fclose( textfile );
  444. }
  445. textfile = fopen( "resources/out/textfile.txt", "r" );
  446. TIXMLASSERT( textfile );
  447. if ( textfile )
  448. {
  449. char buf[ 1024 ];
  450. fgets( buf, 1024, textfile );
  451. XMLTest( "Entity transformation: write. ",
  452. "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
  453. " It also has &lt;, &gt;, and &amp;, as well as a fake copyright \xC2\xA9.\"/>\n",
  454. buf, false );
  455. fclose( textfile );
  456. }
  457. }
  458. {
  459. // Suppress entities.
  460. const char* passages =
  461. "<?xml version=\"1.0\" standalone=\"no\" ?>"
  462. "<passages count=\"006\" formatversion=\"20020620\">"
  463. "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;.\">Crazy &ttk;</psg>"
  464. "</passages>";
  465. XMLDocument doc( false );
  466. doc.Parse( passages );
  467. XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->Attribute( "context" ),
  468. "Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;." );
  469. XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->FirstChild()->Value(),
  470. "Crazy &ttk;" );
  471. doc.Print();
  472. }
  473. {
  474. const char* test = "<?xml version='1.0'?><a.elem xmi.version='2.0'/>";
  475. XMLDocument doc;
  476. doc.Parse( test );
  477. XMLTest( "dot in names", doc.Error(), false );
  478. XMLTest( "dot in names", doc.FirstChildElement()->Name(), "a.elem" );
  479. XMLTest( "dot in names", doc.FirstChildElement()->Attribute( "xmi.version" ), "2.0" );
  480. }
  481. {
  482. const char* test = "<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>";
  483. XMLDocument doc;
  484. doc.Parse( test );
  485. XMLText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
  486. XMLTest( "Entity with one digit.",
  487. text->Value(), "1.1 Start easy ignore fin thickness\n",
  488. false );
  489. }
  490. {
  491. // DOCTYPE not preserved (950171)
  492. //
  493. const char* doctype =
  494. "<?xml version=\"1.0\" ?>"
  495. "<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
  496. "<!ELEMENT title (#PCDATA)>"
  497. "<!ELEMENT books (title,authors)>"
  498. "<element />";
  499. XMLDocument doc;
  500. doc.Parse( doctype );
  501. doc.SaveFile( "resources/out/test7.xml" );
  502. doc.DeleteChild( doc.RootElement() );
  503. doc.LoadFile( "resources/out/test7.xml" );
  504. doc.Print();
  505. const XMLUnknown* decl = doc.FirstChild()->NextSibling()->ToUnknown();
  506. XMLTest( "Correct value of unknown.", "DOCTYPE PLAY SYSTEM 'play.dtd'", decl->Value() );
  507. }
  508. {
  509. // Comments do not stream out correctly.
  510. const char* doctype =
  511. "<!-- Somewhat<evil> -->";
  512. XMLDocument doc;
  513. doc.Parse( doctype );
  514. XMLComment* comment = doc.FirstChild()->ToComment();
  515. XMLTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
  516. }
  517. {
  518. // Double attributes
  519. const char* doctype = "<element attr='red' attr='blue' />";
  520. XMLDocument doc;
  521. doc.Parse( doctype );
  522. XMLTest( "Parsing repeated attributes.", (int)XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() ); // is an error to tinyxml (didn't use to be, but caused issues)
  523. doc.PrintError();
  524. }
  525. {
  526. // Embedded null in stream.
  527. const char* doctype = "<element att\0r='red' attr='blue' />";
  528. XMLDocument doc;
  529. doc.Parse( doctype );
  530. XMLTest( "Embedded null throws error.", true, doc.Error() );
  531. }
  532. {
  533. // Empty documents should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717
  534. const char* str = " ";
  535. XMLDocument doc;
  536. doc.Parse( str );
  537. XMLTest( "Empty document error", (int)XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() );
  538. }
  539. {
  540. // Low entities
  541. XMLDocument doc;
  542. doc.Parse( "<test>&#x0e;</test>" );
  543. const char result[] = { 0x0e, 0 };
  544. XMLTest( "Low entities.", doc.FirstChildElement()->GetText(), result );
  545. doc.Print();
  546. }
  547. {
  548. // Attribute values with trailing quotes not handled correctly
  549. XMLDocument doc;
  550. doc.Parse( "<foo attribute=bar\" />" );
  551. XMLTest( "Throw error with bad end quotes.", doc.Error(), true );
  552. }
  553. {
  554. // [ 1663758 ] Failure to report error on bad XML
  555. XMLDocument xml;
  556. xml.Parse("<x>");
  557. XMLTest("Missing end tag at end of input", xml.Error(), true);
  558. xml.Parse("<x> ");
  559. XMLTest("Missing end tag with trailing whitespace", xml.Error(), true);
  560. xml.Parse("<x></y>");
  561. XMLTest("Mismatched tags", xml.ErrorID(), (int)XML_ERROR_MISMATCHED_ELEMENT);
  562. }
  563. {
  564. // [ 1475201 ] TinyXML parses entities in comments
  565. XMLDocument xml;
  566. xml.Parse("<!-- declarations for <head> & <body> -->"
  567. "<!-- far &amp; away -->" );
  568. XMLNode* e0 = xml.FirstChild();
  569. XMLNode* e1 = e0->NextSibling();
  570. XMLComment* c0 = e0->ToComment();
  571. XMLComment* c1 = e1->ToComment();
  572. XMLTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
  573. XMLTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
  574. }
  575. {
  576. XMLDocument xml;
  577. xml.Parse( "<Parent>"
  578. "<child1 att=''/>"
  579. "<!-- With this comment, child2 will not be parsed! -->"
  580. "<child2 att=''/>"
  581. "</Parent>" );
  582. xml.Print();
  583. int count = 0;
  584. for( XMLNode* ele = xml.FirstChildElement( "Parent" )->FirstChild();
  585. ele;
  586. ele = ele->NextSibling() )
  587. {
  588. ++count;
  589. }
  590. XMLTest( "Comments iterate correctly.", 3, count );
  591. }
  592. {
  593. // trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well.
  594. unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl";
  595. buf[60] = 239;
  596. buf[61] = 0;
  597. XMLDocument doc;
  598. doc.Parse( (const char*)buf);
  599. }
  600. {
  601. // bug 1827248 Error while parsing a little bit malformed file
  602. // Actually not malformed - should work.
  603. XMLDocument xml;
  604. xml.Parse( "<attributelist> </attributelist >" );
  605. XMLTest( "Handle end tag whitespace", false, xml.Error() );
  606. }
  607. {
  608. // This one must not result in an infinite loop
  609. XMLDocument xml;
  610. xml.Parse( "<infinite>loop" );
  611. XMLTest( "Infinite loop test.", true, true );
  612. }
  613. #endif
  614. {
  615. const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>";
  616. XMLDocument doc;
  617. doc.Parse( pub );
  618. XMLDocument clone;
  619. for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) {
  620. XMLNode* copy = node->ShallowClone( &clone );
  621. clone.InsertEndChild( copy );
  622. }
  623. clone.Print();
  624. int count=0;
  625. const XMLNode* a=clone.FirstChild();
  626. const XMLNode* b=doc.FirstChild();
  627. for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) {
  628. ++count;
  629. XMLTest( "Clone and Equal", true, a->ShallowEqual( b ));
  630. }
  631. XMLTest( "Clone and Equal", 4, count );
  632. }
  633. {
  634. // This shouldn't crash.
  635. XMLDocument doc;
  636. if(XML_NO_ERROR != doc.LoadFile( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ))
  637. {
  638. doc.PrintError();
  639. }
  640. XMLTest( "Error in snprinf handling.", true, doc.Error() );
  641. }
  642. {
  643. // Attribute ordering.
  644. static const char* xml = "<element attrib1=\"1\" attrib2=\"2\" attrib3=\"3\" />";
  645. XMLDocument doc;
  646. doc.Parse( xml );
  647. XMLElement* ele = doc.FirstChildElement();
  648. const XMLAttribute* a = ele->FirstAttribute();
  649. XMLTest( "Attribute order", "1", a->Value() );
  650. a = a->Next();
  651. XMLTest( "Attribute order", "2", a->Value() );
  652. a = a->Next();
  653. XMLTest( "Attribute order", "3", a->Value() );
  654. XMLTest( "Attribute order", "attrib3", a->Name() );
  655. ele->DeleteAttribute( "attrib2" );
  656. a = ele->FirstAttribute();
  657. XMLTest( "Attribute order", "1", a->Value() );
  658. a = a->Next();
  659. XMLTest( "Attribute order", "3", a->Value() );
  660. ele->DeleteAttribute( "attrib1" );
  661. ele->DeleteAttribute( "attrib3" );
  662. XMLTest( "Attribute order (empty)", false, ele->FirstAttribute() ? true : false );
  663. }
  664. {
  665. // Make sure an attribute with a space in it succeeds.
  666. static const char* xml0 = "<element attribute1= \"Test Attribute\"/>";
  667. static const char* xml1 = "<element attribute1 =\"Test Attribute\"/>";
  668. static const char* xml2 = "<element attribute1 = \"Test Attribute\"/>";
  669. XMLDocument doc0;
  670. doc0.Parse( xml0 );
  671. XMLDocument doc1;
  672. doc1.Parse( xml1 );
  673. XMLDocument doc2;
  674. doc2.Parse( xml2 );
  675. XMLElement* ele = 0;
  676. ele = doc0.FirstChildElement();
  677. XMLTest( "Attribute with space #1", "Test Attribute", ele->Attribute( "attribute1" ) );
  678. ele = doc1.FirstChildElement();
  679. XMLTest( "Attribute with space #2", "Test Attribute", ele->Attribute( "attribute1" ) );
  680. ele = doc2.FirstChildElement();
  681. XMLTest( "Attribute with space #3", "Test Attribute", ele->Attribute( "attribute1" ) );
  682. }
  683. {
  684. // Make sure we don't go into an infinite loop.
  685. static const char* xml = "<doc><element attribute='attribute'/><element attribute='attribute'/></doc>";
  686. XMLDocument doc;
  687. doc.Parse( xml );
  688. XMLElement* ele0 = doc.FirstChildElement()->FirstChildElement();
  689. XMLElement* ele1 = ele0->NextSiblingElement();
  690. bool equal = ele0->ShallowEqual( ele1 );
  691. XMLTest( "Infinite loop in shallow equal.", true, equal );
  692. }
  693. // -------- Handles ------------
  694. {
  695. static const char* xml = "<element attrib='bar'><sub>Text</sub></element>";
  696. XMLDocument doc;
  697. doc.Parse( xml );
  698. XMLElement* ele = XMLHandle( doc ).FirstChildElement( "element" ).FirstChild().ToElement();
  699. XMLTest( "Handle, success, mutable", ele->Value(), "sub" );
  700. XMLHandle docH( doc );
  701. ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement();
  702. XMLTest( "Handle, dne, mutable", false, ele != 0 );
  703. }
  704. {
  705. static const char* xml = "<element attrib='bar'><sub>Text</sub></element>";
  706. XMLDocument doc;
  707. doc.Parse( xml );
  708. XMLConstHandle docH( doc );
  709. const XMLElement* ele = docH.FirstChildElement( "element" ).FirstChild().ToElement();
  710. XMLTest( "Handle, success, const", ele->Value(), "sub" );
  711. ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement();
  712. XMLTest( "Handle, dne, const", false, ele != 0 );
  713. }
  714. {
  715. // Default Declaration & BOM
  716. XMLDocument doc;
  717. doc.InsertEndChild( doc.NewDeclaration() );
  718. doc.SetBOM( true );
  719. XMLPrinter printer;
  720. doc.Print( &printer );
  721. static const char* result = "\xef\xbb\xbf<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
  722. XMLTest( "BOM and default declaration", printer.CStr(), result, false );
  723. XMLTest( "CStrSize", printer.CStrSize(), 42, false );
  724. }
  725. {
  726. const char* xml = "<ipxml ws='1'><info bla=' /></ipxml>";
  727. XMLDocument doc;
  728. doc.Parse( xml );
  729. XMLTest( "Ill formed XML", true, doc.Error() );
  730. }
  731. // QueryXYZText
  732. {
  733. const char* xml = "<point> <x>1.2</x> <y>1</y> <z>38</z> <valid>true</valid> </point>";
  734. XMLDocument doc;
  735. doc.Parse( xml );
  736. const XMLElement* pointElement = doc.RootElement();
  737. int intValue = 0;
  738. unsigned unsignedValue = 0;
  739. float floatValue = 0;
  740. double doubleValue = 0;
  741. bool boolValue = false;
  742. pointElement->FirstChildElement( "y" )->QueryIntText( &intValue );
  743. pointElement->FirstChildElement( "y" )->QueryUnsignedText( &unsignedValue );
  744. pointElement->FirstChildElement( "x" )->QueryFloatText( &floatValue );
  745. pointElement->FirstChildElement( "x" )->QueryDoubleText( &doubleValue );
  746. pointElement->FirstChildElement( "valid" )->QueryBoolText( &boolValue );
  747. XMLTest( "QueryIntText", intValue, 1, false );
  748. XMLTest( "QueryUnsignedText", unsignedValue, (unsigned)1, false );
  749. XMLTest( "QueryFloatText", floatValue, 1.2f, false );
  750. XMLTest( "QueryDoubleText", doubleValue, 1.2, false );
  751. XMLTest( "QueryBoolText", boolValue, true, false );
  752. }
  753. {
  754. const char* xml = "<element><_sub/><:sub/><sub:sub/><sub-sub/></element>";
  755. XMLDocument doc;
  756. doc.Parse( xml );
  757. XMLTest( "Non-alpha element lead letter parses.", doc.Error(), false );
  758. }
  759. {
  760. const char* xml = "<element/>WOA THIS ISN'T GOING TO PARSE";
  761. XMLDocument doc;
  762. doc.Parse( xml, 10 );
  763. XMLTest( "Set length of incoming data", doc.Error(), false );
  764. }
  765. // ----------- Whitespace ------------
  766. {
  767. const char* xml = "<element>"
  768. "<a> This \nis &apos; text &apos; </a>"
  769. "<b> This is &apos; text &apos; \n</b>"
  770. "<c>This is &apos; \n\n text &apos;</c>"
  771. "</element>";
  772. XMLDocument doc( true, COLLAPSE_WHITESPACE );
  773. doc.Parse( xml );
  774. const XMLElement* element = doc.FirstChildElement();
  775. for( const XMLElement* parent = element->FirstChildElement();
  776. parent;
  777. parent = parent->NextSiblingElement() )
  778. {
  779. XMLTest( "Whitespace collapse", "This is ' text '", parent->GetText() );
  780. }
  781. }
  782. {
  783. const char* xml = "<element> </element>";
  784. XMLDocument doc( true, COLLAPSE_WHITESPACE );
  785. doc.Parse( xml );
  786. XMLTest( "Whitespace all space", true, 0 == doc.FirstChildElement()->FirstChild() );
  787. }
  788. #if 0 // the question being explored is what kind of print to use:
  789. // https://github.com/leethomason/tinyxml2/issues/63
  790. {
  791. const char* xml = "<element attrA='123456789.123456789' attrB='1.001e9'/>";
  792. XMLDocument doc;
  793. doc.Parse( xml );
  794. doc.FirstChildElement()->SetAttribute( "attrA", 123456789.123456789 );
  795. doc.FirstChildElement()->SetAttribute( "attrB", 1.001e9 );
  796. doc.Print();
  797. }
  798. #endif
  799. // ----------- Performance tracking --------------
  800. {
  801. #if defined( _MSC_VER )
  802. __int64 start, end, freq;
  803. QueryPerformanceFrequency( (LARGE_INTEGER*) &freq );
  804. #endif
  805. FILE* fp = fopen( "resources/dream.xml", "r" );
  806. fseek( fp, 0, SEEK_END );
  807. long size = ftell( fp );
  808. fseek( fp, 0, SEEK_SET );
  809. char* mem = new char[size+1];
  810. fread( mem, size, 1, fp );
  811. fclose( fp );
  812. mem[size] = 0;
  813. #if defined( _MSC_VER )
  814. QueryPerformanceCounter( (LARGE_INTEGER*) &start );
  815. #else
  816. clock_t cstart = clock();
  817. #endif
  818. static const int COUNT = 10;
  819. for( int i=0; i<COUNT; ++i ) {
  820. XMLDocument doc;
  821. doc.Parse( mem );
  822. }
  823. #if defined( _MSC_VER )
  824. QueryPerformanceCounter( (LARGE_INTEGER*) &end );
  825. #else
  826. clock_t cend = clock();
  827. #endif
  828. delete [] mem;
  829. static const char* note =
  830. #ifdef DEBUG
  831. "DEBUG";
  832. #else
  833. "Release";
  834. #endif
  835. #if defined( _MSC_VER )
  836. printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, 1000.0 * (double)(end-start) / ( (double)freq * (double)COUNT) );
  837. #else
  838. printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, (double)(cend - cstart)/(double)COUNT );
  839. #endif
  840. }
  841. #if defined( _MSC_VER ) && defined( DEBUG )
  842. _CrtMemCheckpoint( &endMemState );
  843. //_CrtMemDumpStatistics( &endMemState );
  844. _CrtMemState diffMemState;
  845. _CrtMemDifference( &diffMemState, &startMemState, &endMemState );
  846. _CrtMemDumpStatistics( &diffMemState );
  847. //printf( "new total=%d\n", gNewTotal );
  848. #endif
  849. printf ("\nPass %d, Fail %d\n", gPass, gFail);
  850. return 0;
  851. }