xmltest.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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. #if 0
  783. {
  784. // Passes if assert doesn't fire.
  785. XMLDocument xmlDoc;
  786. xmlDoc.NewDeclaration();
  787. xmlDoc.NewComment("Configuration file");
  788. XMLElement *root = xmlDoc.NewElement("settings");
  789. root->SetAttribute("version", 2);
  790. }
  791. #endif
  792. {
  793. const char* xml = "<element> </element>";
  794. XMLDocument doc( true, COLLAPSE_WHITESPACE );
  795. doc.Parse( xml );
  796. XMLTest( "Whitespace all space", true, 0 == doc.FirstChildElement()->FirstChild() );
  797. }
  798. #if 0 // the question being explored is what kind of print to use:
  799. // https://github.com/leethomason/tinyxml2/issues/63
  800. {
  801. const char* xml = "<element attrA='123456789.123456789' attrB='1.001e9'/>";
  802. XMLDocument doc;
  803. doc.Parse( xml );
  804. doc.FirstChildElement()->SetAttribute( "attrA", 123456789.123456789 );
  805. doc.FirstChildElement()->SetAttribute( "attrB", 1.001e9 );
  806. doc.Print();
  807. }
  808. #endif
  809. // ----------- Performance tracking --------------
  810. {
  811. #if defined( _MSC_VER )
  812. __int64 start, end, freq;
  813. QueryPerformanceFrequency( (LARGE_INTEGER*) &freq );
  814. #endif
  815. FILE* fp = fopen( "resources/dream.xml", "r" );
  816. fseek( fp, 0, SEEK_END );
  817. long size = ftell( fp );
  818. fseek( fp, 0, SEEK_SET );
  819. char* mem = new char[size+1];
  820. fread( mem, size, 1, fp );
  821. fclose( fp );
  822. mem[size] = 0;
  823. #if defined( _MSC_VER )
  824. QueryPerformanceCounter( (LARGE_INTEGER*) &start );
  825. #else
  826. clock_t cstart = clock();
  827. #endif
  828. static const int COUNT = 10;
  829. for( int i=0; i<COUNT; ++i ) {
  830. XMLDocument doc;
  831. doc.Parse( mem );
  832. }
  833. #if defined( _MSC_VER )
  834. QueryPerformanceCounter( (LARGE_INTEGER*) &end );
  835. #else
  836. clock_t cend = clock();
  837. #endif
  838. delete [] mem;
  839. static const char* note =
  840. #ifdef DEBUG
  841. "DEBUG";
  842. #else
  843. "Release";
  844. #endif
  845. #if defined( _MSC_VER )
  846. printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, 1000.0 * (double)(end-start) / ( (double)freq * (double)COUNT) );
  847. #else
  848. printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, (double)(cend - cstart)/(double)COUNT );
  849. #endif
  850. }
  851. #if defined( _MSC_VER ) && defined( DEBUG )
  852. _CrtMemCheckpoint( &endMemState );
  853. //_CrtMemDumpStatistics( &endMemState );
  854. _CrtMemState diffMemState;
  855. _CrtMemDifference( &diffMemState, &startMemState, &endMemState );
  856. _CrtMemDumpStatistics( &diffMemState );
  857. //printf( "new total=%d\n", gNewTotal );
  858. #endif
  859. printf ("\nPass %d, Fail %d\n", gPass, gFail);
  860. return 0;
  861. }