xmltest.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  1. #if defined( _MSC_VER )
  2. #if !defined( _CRT_SECURE_NO_WARNINGS )
  3. #define _CRT_SECURE_NO_WARNINGS // This test file is not intended to be secure.
  4. #endif
  5. #endif
  6. #include "tinyxml2.h"
  7. #include <cstdlib>
  8. #include <cstring>
  9. #include <ctime>
  10. #if defined( _MSC_VER )
  11. #include <direct.h> // _mkdir
  12. #include <crtdbg.h>
  13. #define WIN32_LEAN_AND_MEAN
  14. #include <windows.h>
  15. _CrtMemState startMemState;
  16. _CrtMemState endMemState;
  17. #elif defined(MINGW32) || defined(__MINGW32__)
  18. #include <io.h> // mkdir
  19. #else
  20. #include <sys/stat.h> // mkdir
  21. #endif
  22. using namespace tinyxml2;
  23. using namespace std;
  24. int gPass = 0;
  25. int gFail = 0;
  26. bool XMLTest (const char* testString, const char* expected, const char* found, bool echo=true, bool extraNL=false )
  27. {
  28. bool pass;
  29. if ( !expected && !found )
  30. pass = true;
  31. else if ( !expected || !found )
  32. pass = false;
  33. else
  34. pass = !strcmp( expected, found );
  35. if ( pass )
  36. printf ("[pass]");
  37. else
  38. printf ("[fail]");
  39. if ( !echo ) {
  40. printf (" %s\n", testString);
  41. }
  42. else {
  43. if ( extraNL ) {
  44. printf( " %s\n", testString );
  45. printf( "%s\n", expected );
  46. printf( "%s\n", found );
  47. }
  48. else {
  49. printf (" %s [%s][%s]\n", testString, expected, found);
  50. }
  51. }
  52. if ( pass )
  53. ++gPass;
  54. else
  55. ++gFail;
  56. return pass;
  57. }
  58. template< class T > bool XMLTest( const char* testString, T expected, T found, bool echo=true )
  59. {
  60. bool pass = ( expected == found );
  61. if ( pass )
  62. printf ("[pass]");
  63. else
  64. printf ("[fail]");
  65. if ( !echo )
  66. printf (" %s\n", testString);
  67. else
  68. printf (" %s [%d][%d]\n", testString, static_cast<int>(expected), static_cast<int>(found) );
  69. if ( pass )
  70. ++gPass;
  71. else
  72. ++gFail;
  73. return pass;
  74. }
  75. void NullLineEndings( char* p )
  76. {
  77. while( p && *p ) {
  78. if ( *p == '\n' || *p == '\r' ) {
  79. *p = 0;
  80. return;
  81. }
  82. ++p;
  83. }
  84. }
  85. int example_1()
  86. {
  87. XMLDocument doc;
  88. doc.LoadFile( "resources/dream.xml" );
  89. return doc.ErrorID();
  90. }
  91. /** @page Example-1 Load an XML File
  92. * @dontinclude ./xmltest.cpp
  93. * Basic XML file loading.
  94. * The basic syntax to load an XML file from
  95. * disk and check for an error. (ErrorID()
  96. * will return 0 for no error.)
  97. * @skip example_1()
  98. * @until }
  99. */
  100. int example_2()
  101. {
  102. static const char* xml = "<element/>";
  103. XMLDocument doc;
  104. doc.Parse( xml );
  105. return doc.ErrorID();
  106. }
  107. /** @page Example-2 Parse an XML from char buffer
  108. * @dontinclude ./xmltest.cpp
  109. * Basic XML string parsing.
  110. * The basic syntax to parse an XML for
  111. * a char* and check for an error. (ErrorID()
  112. * will return 0 for no error.)
  113. * @skip example_2()
  114. * @until }
  115. */
  116. int example_3()
  117. {
  118. static const char* xml =
  119. "<?xml version=\"1.0\"?>"
  120. "<!DOCTYPE PLAY SYSTEM \"play.dtd\">"
  121. "<PLAY>"
  122. "<TITLE>A Midsummer Night's Dream</TITLE>"
  123. "</PLAY>";
  124. XMLDocument doc;
  125. doc.Parse( xml );
  126. XMLElement* titleElement = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" );
  127. const char* title = titleElement->GetText();
  128. printf( "Name of play (1): %s\n", title );
  129. XMLText* textNode = titleElement->FirstChild()->ToText();
  130. title = textNode->Value();
  131. printf( "Name of play (2): %s\n", title );
  132. return doc.ErrorID();
  133. }
  134. /** @page Example-3 Get information out of XML
  135. @dontinclude ./xmltest.cpp
  136. In this example, we navigate a simple XML
  137. file, and read some interesting text. Note
  138. that this example doesn't use error
  139. checking; working code should check for null
  140. pointers when walking an XML tree, or use
  141. XMLHandle.
  142. (The XML is an excerpt from "dream.xml").
  143. @skip example_3()
  144. @until </PLAY>";
  145. The structure of the XML file is:
  146. <ul>
  147. <li>(declaration)</li>
  148. <li>(dtd stuff)</li>
  149. <li>Element "PLAY"</li>
  150. <ul>
  151. <li>Element "TITLE"</li>
  152. <ul>
  153. <li>Text "A Midsummer Night's Dream"</li>
  154. </ul>
  155. </ul>
  156. </ul>
  157. For this example, we want to print out the
  158. title of the play. The text of the title (what
  159. we want) is child of the "TITLE" element which
  160. is a child of the "PLAY" element.
  161. We want to skip the declaration and dtd, so the
  162. method FirstChildElement() is a good choice. The
  163. FirstChildElement() of the Document is the "PLAY"
  164. Element, the FirstChildElement() of the "PLAY" Element
  165. is the "TITLE" Element.
  166. @until ( "TITLE" );
  167. We can then use the convenience function GetText()
  168. to get the title of the play.
  169. @until title );
  170. Text is just another Node in the XML DOM. And in
  171. fact you should be a little cautious with it, as
  172. text nodes can contain elements.
  173. @verbatim
  174. Consider: A Midsummer Night's <b>Dream</b>
  175. @endverbatim
  176. It is more correct to actually query the Text Node
  177. if in doubt:
  178. @until title );
  179. Noting that here we use FirstChild() since we are
  180. looking for XMLText, not an element, and ToText()
  181. is a cast from a Node to a XMLText.
  182. */
  183. bool example_4()
  184. {
  185. static const char* xml =
  186. "<information>"
  187. " <attributeApproach v='2' />"
  188. " <textApproach>"
  189. " <v>2</v>"
  190. " </textApproach>"
  191. "</information>";
  192. XMLDocument doc;
  193. doc.Parse( xml );
  194. int v0 = 0;
  195. int v1 = 0;
  196. XMLElement* attributeApproachElement = doc.FirstChildElement()->FirstChildElement( "attributeApproach" );
  197. attributeApproachElement->QueryIntAttribute( "v", &v0 );
  198. XMLElement* textApproachElement = doc.FirstChildElement()->FirstChildElement( "textApproach" );
  199. textApproachElement->FirstChildElement( "v" )->QueryIntText( &v1 );
  200. printf( "Both values are the same: %d and %d\n", v0, v1 );
  201. return !doc.Error() && ( v0 == v1 );
  202. }
  203. /** @page Example-4 Read attributes and text information.
  204. @dontinclude ./xmltest.cpp
  205. There are fundamentally 2 ways of writing a key-value
  206. pair into an XML file. (Something that's always annoyed
  207. me about XML.) Either by using attributes, or by writing
  208. the key name into an element and the value into
  209. the text node wrapped by the element. Both approaches
  210. are illustrated in this example, which shows two ways
  211. to encode the value "2" into the key "v":
  212. @skip example_4()
  213. @until "</information>";
  214. TinyXML-2 has accessors for both approaches.
  215. When using an attribute, you navigate to the XMLElement
  216. with that attribute and use the QueryIntAttribute()
  217. group of methods. (Also QueryFloatAttribute(), etc.)
  218. @skip XMLElement* attributeApproachElement
  219. @until &v0 );
  220. When using the text approach, you need to navigate
  221. down one more step to the XMLElement that contains
  222. the text. Note the extra FirstChildElement( "v" )
  223. in the code below. The value of the text can then
  224. be safely queried with the QueryIntText() group
  225. of methods. (Also QueryFloatText(), etc.)
  226. @skip XMLElement* textApproachElement
  227. @until &v1 );
  228. */
  229. int main( int argc, const char ** argv )
  230. {
  231. #if defined( _MSC_VER ) && defined( DEBUG )
  232. _CrtMemCheckpoint( &startMemState );
  233. // Enable MS Visual C++ debug heap memory leaks dump on exit
  234. _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
  235. #endif
  236. #if defined(_MSC_VER) || defined(MINGW32) || defined(__MINGW32__)
  237. #if defined __MINGW64_VERSION_MAJOR && defined __MINGW64_VERSION_MINOR
  238. //MINGW64: both 32 and 64-bit
  239. mkdir( "resources/out/" );
  240. #else
  241. _mkdir( "resources/out/" );
  242. #endif
  243. #else
  244. mkdir( "resources/out/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  245. #endif
  246. {
  247. TIXMLASSERT( true );
  248. }
  249. if ( argc > 1 ) {
  250. XMLDocument* doc = new XMLDocument();
  251. clock_t startTime = clock();
  252. doc->LoadFile( argv[1] );
  253. clock_t loadTime = clock();
  254. int errorID = doc->ErrorID();
  255. delete doc; doc = 0;
  256. clock_t deleteTime = clock();
  257. printf( "Test file '%s' loaded. ErrorID=%d\n", argv[1], errorID );
  258. if ( !errorID ) {
  259. printf( "Load time=%u\n", (unsigned)(loadTime - startTime) );
  260. printf( "Delete time=%u\n", (unsigned)(deleteTime - loadTime) );
  261. printf( "Total time=%u\n", (unsigned)(deleteTime - startTime) );
  262. }
  263. exit(0);
  264. }
  265. FILE* fp = fopen( "resources/dream.xml", "r" );
  266. if ( !fp ) {
  267. printf( "Error opening test file 'dream.xml'.\n"
  268. "Is your working directory the same as where \n"
  269. "the xmltest.cpp and dream.xml file are?\n\n"
  270. #if defined( _MSC_VER )
  271. "In windows Visual Studio you may need to set\n"
  272. "Properties->Debugging->Working Directory to '..'\n"
  273. #endif
  274. );
  275. exit( 1 );
  276. }
  277. fclose( fp );
  278. XMLTest( "Example-1", 0, example_1() );
  279. XMLTest( "Example-2", 0, example_2() );
  280. XMLTest( "Example-3", 0, example_3() );
  281. XMLTest( "Example-4", true, example_4() );
  282. /* ------ Example 2: Lookup information. ---- */
  283. {
  284. static const char* test[] = { "<element />",
  285. "<element></element>",
  286. "<element><subelement/></element>",
  287. "<element><subelement></subelement></element>",
  288. "<element><subelement><subsub/></subelement></element>",
  289. "<!--comment beside elements--><element><subelement></subelement></element>",
  290. "<!--comment beside elements, this time with spaces--> \n <element> <subelement> \n </subelement> </element>",
  291. "<element attrib1='foo' attrib2=\"bar\" ></element>",
  292. "<element attrib1='foo' attrib2=\"bar\" ><subelement attrib3='yeehaa' /></element>",
  293. "<element>Text inside element.</element>",
  294. "<element><b></b></element>",
  295. "<element>Text inside and <b>bolded</b> in the element.</element>",
  296. "<outer><element>Text inside and <b>bolded</b> in the element.</element></outer>",
  297. "<element>This &amp; That.</element>",
  298. "<element attrib='This&lt;That' />",
  299. 0
  300. };
  301. for( int i=0; test[i]; ++i ) {
  302. XMLDocument doc;
  303. doc.Parse( test[i] );
  304. doc.Print();
  305. printf( "----------------------------------------------\n" );
  306. }
  307. }
  308. #if 1
  309. {
  310. static const char* test = "<!--hello world\n"
  311. " line 2\r"
  312. " line 3\r\n"
  313. " line 4\n\r"
  314. " line 5\r-->";
  315. XMLDocument doc;
  316. doc.Parse( test );
  317. doc.Print();
  318. }
  319. {
  320. static const char* test = "<element>Text before.</element>";
  321. XMLDocument doc;
  322. doc.Parse( test );
  323. XMLElement* root = doc.FirstChildElement();
  324. XMLElement* newElement = doc.NewElement( "Subelement" );
  325. root->InsertEndChild( newElement );
  326. doc.Print();
  327. }
  328. {
  329. XMLDocument* doc = new XMLDocument();
  330. static const char* test = "<element><sub/></element>";
  331. doc->Parse( test );
  332. delete doc;
  333. }
  334. {
  335. // Test: Programmatic DOM
  336. // Build:
  337. // <element>
  338. // <!--comment-->
  339. // <sub attrib="1" />
  340. // <sub attrib="2" />
  341. // <sub attrib="3" >& Text!</sub>
  342. // <element>
  343. XMLDocument* doc = new XMLDocument();
  344. XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) );
  345. XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) };
  346. for( int i=0; i<3; ++i ) {
  347. sub[i]->SetAttribute( "attrib", i );
  348. }
  349. element->InsertEndChild( sub[2] );
  350. XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) );
  351. comment->SetUserData((void*)2);
  352. element->InsertAfterChild( comment, sub[0] );
  353. element->InsertAfterChild( sub[0], sub[1] );
  354. sub[2]->InsertFirstChild( doc->NewText( "& Text!" ));
  355. doc->Print();
  356. XMLTest( "Programmatic DOM", "comment", doc->FirstChildElement( "element" )->FirstChild()->Value() );
  357. XMLTest( "Programmatic DOM", "0", doc->FirstChildElement( "element" )->FirstChildElement()->Attribute( "attrib" ) );
  358. XMLTest( "Programmatic DOM", 2, doc->FirstChildElement()->LastChildElement( "sub" )->IntAttribute( "attrib" ) );
  359. XMLTest( "Programmatic DOM", "& Text!",
  360. doc->FirstChildElement()->LastChildElement( "sub" )->FirstChild()->ToText()->Value() );
  361. XMLTest("User data", (void*)2 == comment->GetUserData(), true, false);
  362. // And now deletion:
  363. element->DeleteChild( sub[2] );
  364. doc->DeleteNode( comment );
  365. element->FirstChildElement()->SetAttribute( "attrib", true );
  366. element->LastChildElement()->DeleteAttribute( "attrib" );
  367. XMLTest( "Programmatic DOM", true, doc->FirstChildElement()->FirstChildElement()->BoolAttribute( "attrib" ) );
  368. int value1 = 10;
  369. int value2 = doc->FirstChildElement()->LastChildElement()->IntAttribute( "attrib", 10 );
  370. int result = doc->FirstChildElement()->LastChildElement()->QueryIntAttribute( "attrib", &value1 );
  371. XMLTest( "Programmatic DOM", result, (int)XML_NO_ATTRIBUTE );
  372. XMLTest( "Programmatic DOM", value1, 10 );
  373. XMLTest( "Programmatic DOM", value2, 10 );
  374. doc->Print();
  375. {
  376. XMLPrinter streamer;
  377. doc->Print( &streamer );
  378. printf( "%s", streamer.CStr() );
  379. }
  380. {
  381. XMLPrinter streamer( 0, true );
  382. doc->Print( &streamer );
  383. XMLTest( "Compact mode", "<element><sub attrib=\"true\"/><sub/></element>", streamer.CStr(), false );
  384. }
  385. doc->SaveFile( "./resources/out/pretty.xml" );
  386. doc->SaveFile( "./resources/out/compact.xml", true );
  387. delete doc;
  388. }
  389. {
  390. // Test: Dream
  391. // XML1 : 1,187,569 bytes in 31,209 allocations
  392. // XML2 : 469,073 bytes in 323 allocations
  393. //int newStart = gNew;
  394. XMLDocument doc;
  395. doc.LoadFile( "resources/dream.xml" );
  396. doc.SaveFile( "resources/out/dreamout.xml" );
  397. doc.PrintError();
  398. XMLTest( "Dream", "xml version=\"1.0\"",
  399. doc.FirstChild()->ToDeclaration()->Value() );
  400. XMLTest( "Dream", true, doc.FirstChild()->NextSibling()->ToUnknown() ? true : false );
  401. XMLTest( "Dream", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
  402. doc.FirstChild()->NextSibling()->ToUnknown()->Value() );
  403. XMLTest( "Dream", "And Robin shall restore amends.",
  404. doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
  405. XMLTest( "Dream", "And Robin shall restore amends.",
  406. doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
  407. XMLDocument doc2;
  408. doc2.LoadFile( "resources/out/dreamout.xml" );
  409. XMLTest( "Dream-out", "xml version=\"1.0\"",
  410. doc2.FirstChild()->ToDeclaration()->Value() );
  411. XMLTest( "Dream-out", true, doc2.FirstChild()->NextSibling()->ToUnknown() ? true : false );
  412. XMLTest( "Dream-out", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
  413. doc2.FirstChild()->NextSibling()->ToUnknown()->Value() );
  414. XMLTest( "Dream-out", "And Robin shall restore amends.",
  415. doc2.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
  416. //gNewTotal = gNew - newStart;
  417. }
  418. {
  419. const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n"
  420. "<passages count=\"006\" formatversion=\"20020620\">\n"
  421. " <wrong error>\n"
  422. "</passages>";
  423. XMLDocument doc;
  424. doc.Parse( error );
  425. XMLTest( "Bad XML", doc.ErrorID(), XML_ERROR_PARSING_ATTRIBUTE );
  426. }
  427. {
  428. const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";
  429. XMLDocument doc;
  430. doc.Parse( str );
  431. XMLElement* ele = doc.FirstChildElement();
  432. int iVal, result;
  433. double dVal;
  434. result = ele->QueryDoubleAttribute( "attr0", &dVal );
  435. XMLTest( "Query attribute: int as double", result, (int)XML_SUCCESS);
  436. XMLTest( "Query attribute: int as double", (int)dVal, 1 );
  437. XMLTest( "Query attribute: int as double", (int)ele->DoubleAttribute("attr0"), 1);
  438. result = ele->QueryDoubleAttribute( "attr1", &dVal );
  439. XMLTest( "Query attribute: double as double", result, (int)XML_SUCCESS);
  440. XMLTest( "Query attribute: double as double", dVal, 2.0 );
  441. XMLTest( "Query attribute: double as double", ele->DoubleAttribute("attr1"), 2.0 );
  442. result = ele->QueryIntAttribute( "attr1", &iVal );
  443. XMLTest( "Query attribute: double as int", result, (int)XML_SUCCESS);
  444. XMLTest( "Query attribute: double as int", iVal, 2 );
  445. result = ele->QueryIntAttribute( "attr2", &iVal );
  446. XMLTest( "Query attribute: not a number", result, (int)XML_WRONG_ATTRIBUTE_TYPE );
  447. XMLTest( "Query attribute: not a number", ele->DoubleAttribute("attr2", 4.0), 4.0 );
  448. result = ele->QueryIntAttribute( "bar", &iVal );
  449. XMLTest( "Query attribute: does not exist", result, (int)XML_NO_ATTRIBUTE );
  450. XMLTest( "Query attribute: does not exist", ele->BoolAttribute("bar", true), true );
  451. }
  452. {
  453. const char* str = "<doc/>";
  454. XMLDocument doc;
  455. doc.Parse( str );
  456. XMLElement* ele = doc.FirstChildElement();
  457. int iVal, iVal2;
  458. double dVal, dVal2;
  459. ele->SetAttribute( "str", "strValue" );
  460. ele->SetAttribute( "int", 1 );
  461. ele->SetAttribute( "double", -1.0 );
  462. const char* cStr = ele->Attribute( "str" );
  463. ele->QueryIntAttribute( "int", &iVal );
  464. ele->QueryDoubleAttribute( "double", &dVal );
  465. ele->QueryAttribute( "int", &iVal2 );
  466. ele->QueryAttribute( "double", &dVal2 );
  467. XMLTest( "Attribute match test", ele->Attribute( "str", "strValue" ), "strValue" );
  468. XMLTest( "Attribute round trip. c-string.", "strValue", cStr );
  469. XMLTest( "Attribute round trip. int.", 1, iVal );
  470. XMLTest( "Attribute round trip. double.", -1, (int)dVal );
  471. XMLTest( "Alternate query", true, iVal == iVal2 );
  472. XMLTest( "Alternate query", true, dVal == dVal2 );
  473. XMLTest( "Alternate query", true, iVal == ele->IntAttribute("int") );
  474. XMLTest( "Alternate query", true, dVal == ele->DoubleAttribute("double") );
  475. }
  476. {
  477. XMLDocument doc;
  478. doc.LoadFile( "resources/utf8test.xml" );
  479. // Get the attribute "value" from the "Russian" element and check it.
  480. XMLElement* element = doc.FirstChildElement( "document" )->FirstChildElement( "Russian" );
  481. const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU,
  482. 0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 };
  483. XMLTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ) );
  484. const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U,
  485. 0xd1U, 0x81U, 0xd1U, 0x81U,
  486. 0xd0U, 0xbaU, 0xd0U, 0xb8U,
  487. 0xd0U, 0xb9U, 0 };
  488. const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";
  489. XMLText* text = doc.FirstChildElement( "document" )->FirstChildElement( (const char*) russianElementName )->FirstChild()->ToText();
  490. XMLTest( "UTF-8: Browsing russian element name.",
  491. russianText,
  492. text->Value() );
  493. // Now try for a round trip.
  494. doc.SaveFile( "resources/out/utf8testout.xml" );
  495. // Check the round trip.
  496. int okay = 0;
  497. FILE* saved = fopen( "resources/out/utf8testout.xml", "r" );
  498. FILE* verify = fopen( "resources/utf8testverify.xml", "r" );
  499. if ( saved && verify )
  500. {
  501. okay = 1;
  502. char verifyBuf[256];
  503. while ( fgets( verifyBuf, 256, verify ) )
  504. {
  505. char savedBuf[256];
  506. fgets( savedBuf, 256, saved );
  507. NullLineEndings( verifyBuf );
  508. NullLineEndings( savedBuf );
  509. if ( strcmp( verifyBuf, savedBuf ) )
  510. {
  511. printf( "verify:%s<\n", verifyBuf );
  512. printf( "saved :%s<\n", savedBuf );
  513. okay = 0;
  514. break;
  515. }
  516. }
  517. }
  518. if ( saved )
  519. fclose( saved );
  520. if ( verify )
  521. fclose( verify );
  522. XMLTest( "UTF-8: Verified multi-language round trip.", 1, okay );
  523. }
  524. // --------GetText()-----------
  525. {
  526. const char* str = "<foo>This is text</foo>";
  527. XMLDocument doc;
  528. doc.Parse( str );
  529. const XMLElement* element = doc.RootElement();
  530. XMLTest( "GetText() normal use.", "This is text", element->GetText() );
  531. str = "<foo><b>This is text</b></foo>";
  532. doc.Parse( str );
  533. element = doc.RootElement();
  534. XMLTest( "GetText() contained element.", element->GetText() == 0, true );
  535. }
  536. // --------SetText()-----------
  537. {
  538. const char* str = "<foo></foo>";
  539. XMLDocument doc;
  540. doc.Parse( str );
  541. XMLElement* element = doc.RootElement();
  542. element->SetText("darkness.");
  543. XMLTest( "SetText() normal use (open/close).", "darkness.", element->GetText() );
  544. element->SetText("blue flame.");
  545. XMLTest( "SetText() replace.", "blue flame.", element->GetText() );
  546. str = "<foo/>";
  547. doc.Parse( str );
  548. element = doc.RootElement();
  549. element->SetText("The driver");
  550. XMLTest( "SetText() normal use. (self-closing)", "The driver", element->GetText() );
  551. element->SetText("<b>horses</b>");
  552. XMLTest( "SetText() replace with tag-like text.", "<b>horses</b>", element->GetText() );
  553. //doc.Print();
  554. str = "<foo><bar>Text in nested element</bar></foo>";
  555. doc.Parse( str );
  556. element = doc.RootElement();
  557. element->SetText("wolves");
  558. XMLTest( "SetText() prefix to nested non-text children.", "wolves", element->GetText() );
  559. str = "<foo/>";
  560. doc.Parse( str );
  561. element = doc.RootElement();
  562. element->SetText( "str" );
  563. XMLTest( "SetText types", "str", element->GetText() );
  564. element->SetText( 1 );
  565. XMLTest( "SetText types", "1", element->GetText() );
  566. element->SetText( 1U );
  567. XMLTest( "SetText types", "1", element->GetText() );
  568. element->SetText( true );
  569. XMLTest( "SetText types", "true", element->GetText() );
  570. element->SetText( 1.5f );
  571. XMLTest( "SetText types", "1.5", element->GetText() );
  572. element->SetText( 1.5 );
  573. XMLTest( "SetText types", "1.5", element->GetText() );
  574. }
  575. // ---------- Attributes ---------
  576. {
  577. static const int64_t BIG = -123456789012345678;
  578. XMLDocument doc;
  579. XMLElement* element = doc.NewElement("element");
  580. doc.InsertFirstChild(element);
  581. {
  582. element->SetAttribute("attrib", int(-100));
  583. int v = 0;
  584. element->QueryIntAttribute("attrib", &v);
  585. XMLTest("Attribute: int", -100, v, true);
  586. element->QueryAttribute("attrib", &v);
  587. XMLTest("Attribute: int", -100, v, true);
  588. XMLTest("Attribute: int", -100, element->IntAttribute("attrib"), true);
  589. }
  590. {
  591. element->SetAttribute("attrib", unsigned(100));
  592. unsigned v = 0;
  593. element->QueryUnsignedAttribute("attrib", &v);
  594. XMLTest("Attribute: unsigned", unsigned(100), v, true);
  595. element->QueryAttribute("attrib", &v);
  596. XMLTest("Attribute: unsigned", unsigned(100), v, true);
  597. XMLTest("Attribute: unsigned", unsigned(100), element->UnsignedAttribute("attrib"), true);
  598. }
  599. {
  600. element->SetAttribute("attrib", BIG);
  601. int64_t v = 0;
  602. element->QueryInt64Attribute("attrib", &v);
  603. XMLTest("Attribute: int64_t", BIG, v, true);
  604. element->QueryAttribute("attrib", &v);
  605. XMLTest("Attribute: int64_t", BIG, v, true);
  606. XMLTest("Attribute: int64_t", BIG, element->Int64Attribute("attrib"), true);
  607. }
  608. {
  609. element->SetAttribute("attrib", true);
  610. bool v = false;
  611. element->QueryBoolAttribute("attrib", &v);
  612. XMLTest("Attribute: bool", true, v, true);
  613. element->QueryAttribute("attrib", &v);
  614. XMLTest("Attribute: bool", true, v, true);
  615. XMLTest("Attribute: bool", true, element->BoolAttribute("attrib"), true);
  616. }
  617. {
  618. element->SetAttribute("attrib", 100.0);
  619. double v = 0;
  620. element->QueryDoubleAttribute("attrib", &v);
  621. XMLTest("Attribute: double", 100.0, v, true);
  622. element->QueryAttribute("attrib", &v);
  623. XMLTest("Attribute: double", 100.0, v, true);
  624. XMLTest("Attribute: double", 100.0, element->DoubleAttribute("attrib"), true);
  625. }
  626. {
  627. element->SetAttribute("attrib", 100.0f);
  628. float v = 0;
  629. element->QueryFloatAttribute("attrib", &v);
  630. XMLTest("Attribute: float", 100.0f, v, true);
  631. element->QueryAttribute("attrib", &v);
  632. XMLTest("Attribute: float", 100.0f, v, true);
  633. XMLTest("Attribute: float", 100.0f, element->FloatAttribute("attrib"), true);
  634. }
  635. {
  636. element->SetText(BIG);
  637. int64_t v = 0;
  638. element->QueryInt64Text(&v);
  639. XMLTest("Element: int64_t", BIG, v, true);
  640. }
  641. }
  642. // ---------- XMLPrinter stream mode ------
  643. {
  644. {
  645. FILE* printerfp = fopen("resources/printer.xml", "w");
  646. XMLPrinter printer(printerfp);
  647. printer.OpenElement("foo");
  648. printer.PushAttribute("attrib-text", "text");
  649. printer.PushAttribute("attrib-int", int(1));
  650. printer.PushAttribute("attrib-unsigned", unsigned(2));
  651. printer.PushAttribute("attrib-int64", int64_t(3));
  652. printer.PushAttribute("attrib-bool", true);
  653. printer.PushAttribute("attrib-double", 4.0);
  654. printer.CloseElement();
  655. fclose(printerfp);
  656. }
  657. {
  658. XMLDocument doc;
  659. doc.LoadFile("resources/printer.xml");
  660. XMLTest("XMLPrinter Stream mode: load", doc.ErrorID(), XML_SUCCESS, true);
  661. const XMLDocument& cdoc = doc;
  662. const XMLAttribute* attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-text");
  663. XMLTest("attrib-text", "text", attrib->Value(), true);
  664. attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-int");
  665. XMLTest("attrib-int", int(1), attrib->IntValue(), true);
  666. attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-unsigned");
  667. XMLTest("attrib-unsigned", unsigned(2), attrib->UnsignedValue(), true);
  668. attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-int64");
  669. XMLTest("attrib-int64", int64_t(3), attrib->Int64Value(), true);
  670. attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-bool");
  671. XMLTest("attrib-bool", true, attrib->BoolValue(), true);
  672. attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-double");
  673. XMLTest("attrib-double", 4.0, attrib->DoubleValue(), true);
  674. }
  675. }
  676. // ---------- CDATA ---------------
  677. {
  678. const char* str = "<xmlElement>"
  679. "<![CDATA["
  680. "I am > the rules!\n"
  681. "...since I make symbolic puns"
  682. "]]>"
  683. "</xmlElement>";
  684. XMLDocument doc;
  685. doc.Parse( str );
  686. doc.Print();
  687. XMLTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(),
  688. "I am > the rules!\n...since I make symbolic puns",
  689. false );
  690. }
  691. // ----------- CDATA -------------
  692. {
  693. const char* str = "<xmlElement>"
  694. "<![CDATA["
  695. "<b>I am > the rules!</b>\n"
  696. "...since I make symbolic puns"
  697. "]]>"
  698. "</xmlElement>";
  699. XMLDocument doc;
  700. doc.Parse( str );
  701. doc.Print();
  702. XMLTest( "CDATA parse. [ tixml1:1480107 ]", doc.FirstChildElement()->FirstChild()->Value(),
  703. "<b>I am > the rules!</b>\n...since I make symbolic puns",
  704. false );
  705. }
  706. // InsertAfterChild causes crash.
  707. {
  708. // InsertBeforeChild and InsertAfterChild causes crash.
  709. XMLDocument doc;
  710. XMLElement* parent = doc.NewElement( "Parent" );
  711. doc.InsertFirstChild( parent );
  712. XMLElement* childText0 = doc.NewElement( "childText0" );
  713. XMLElement* childText1 = doc.NewElement( "childText1" );
  714. XMLNode* childNode0 = parent->InsertEndChild( childText0 );
  715. XMLNode* childNode1 = parent->InsertAfterChild( childNode0, childText1 );
  716. XMLTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent->LastChild() ), true );
  717. }
  718. {
  719. // Entities not being written correctly.
  720. // From Lynn Allen
  721. const char* passages =
  722. "<?xml version=\"1.0\" standalone=\"no\" ?>"
  723. "<passages count=\"006\" formatversion=\"20020620\">"
  724. "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
  725. " It also has &lt;, &gt;, and &amp;, as well as a fake copyright &#xA9;.\"> </psg>"
  726. "</passages>";
  727. XMLDocument doc;
  728. doc.Parse( passages );
  729. XMLElement* psg = doc.RootElement()->FirstChildElement();
  730. const char* context = psg->Attribute( "context" );
  731. const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";
  732. XMLTest( "Entity transformation: read. ", expected, context, true );
  733. FILE* textfile = fopen( "resources/out/textfile.txt", "w" );
  734. if ( textfile )
  735. {
  736. XMLPrinter streamer( textfile );
  737. psg->Accept( &streamer );
  738. fclose( textfile );
  739. }
  740. textfile = fopen( "resources/out/textfile.txt", "r" );
  741. TIXMLASSERT( textfile );
  742. if ( textfile )
  743. {
  744. char buf[ 1024 ];
  745. fgets( buf, 1024, textfile );
  746. XMLTest( "Entity transformation: write. ",
  747. "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
  748. " It also has &lt;, &gt;, and &amp;, as well as a fake copyright \xC2\xA9.\"/>\n",
  749. buf, false );
  750. fclose( textfile );
  751. }
  752. }
  753. {
  754. // Suppress entities.
  755. const char* passages =
  756. "<?xml version=\"1.0\" standalone=\"no\" ?>"
  757. "<passages count=\"006\" formatversion=\"20020620\">"
  758. "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;.\">Crazy &ttk;</psg>"
  759. "</passages>";
  760. XMLDocument doc( false );
  761. doc.Parse( passages );
  762. XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->Attribute( "context" ),
  763. "Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;." );
  764. XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->FirstChild()->Value(),
  765. "Crazy &ttk;" );
  766. doc.Print();
  767. }
  768. {
  769. const char* test = "<?xml version='1.0'?><a.elem xmi.version='2.0'/>";
  770. XMLDocument doc;
  771. doc.Parse( test );
  772. XMLTest( "dot in names", doc.Error(), false );
  773. XMLTest( "dot in names", doc.FirstChildElement()->Name(), "a.elem" );
  774. XMLTest( "dot in names", doc.FirstChildElement()->Attribute( "xmi.version" ), "2.0" );
  775. }
  776. {
  777. const char* test = "<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>";
  778. XMLDocument doc;
  779. doc.Parse( test );
  780. XMLText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
  781. XMLTest( "Entity with one digit.",
  782. text->Value(), "1.1 Start easy ignore fin thickness\n",
  783. false );
  784. }
  785. {
  786. // DOCTYPE not preserved (950171)
  787. //
  788. const char* doctype =
  789. "<?xml version=\"1.0\" ?>"
  790. "<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
  791. "<!ELEMENT title (#PCDATA)>"
  792. "<!ELEMENT books (title,authors)>"
  793. "<element />";
  794. XMLDocument doc;
  795. doc.Parse( doctype );
  796. doc.SaveFile( "resources/out/test7.xml" );
  797. doc.DeleteChild( doc.RootElement() );
  798. doc.LoadFile( "resources/out/test7.xml" );
  799. doc.Print();
  800. const XMLUnknown* decl = doc.FirstChild()->NextSibling()->ToUnknown();
  801. XMLTest( "Correct value of unknown.", "DOCTYPE PLAY SYSTEM 'play.dtd'", decl->Value() );
  802. }
  803. {
  804. // Comments do not stream out correctly.
  805. const char* doctype =
  806. "<!-- Somewhat<evil> -->";
  807. XMLDocument doc;
  808. doc.Parse( doctype );
  809. XMLComment* comment = doc.FirstChild()->ToComment();
  810. XMLTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
  811. }
  812. {
  813. // Double attributes
  814. const char* doctype = "<element attr='red' attr='blue' />";
  815. XMLDocument doc;
  816. doc.Parse( doctype );
  817. XMLTest( "Parsing repeated attributes.", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() ); // is an error to tinyxml (didn't use to be, but caused issues)
  818. doc.PrintError();
  819. }
  820. {
  821. // Embedded null in stream.
  822. const char* doctype = "<element att\0r='red' attr='blue' />";
  823. XMLDocument doc;
  824. doc.Parse( doctype );
  825. XMLTest( "Embedded null throws error.", true, doc.Error() );
  826. }
  827. {
  828. // Empty documents should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717
  829. const char* str = "";
  830. XMLDocument doc;
  831. doc.Parse( str );
  832. XMLTest( "Empty document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() );
  833. }
  834. {
  835. // Documents with all whitespaces should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717
  836. const char* str = " ";
  837. XMLDocument doc;
  838. doc.Parse( str );
  839. XMLTest( "All whitespaces document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() );
  840. }
  841. {
  842. // Low entities
  843. XMLDocument doc;
  844. doc.Parse( "<test>&#x0e;</test>" );
  845. const char result[] = { 0x0e, 0 };
  846. XMLTest( "Low entities.", doc.FirstChildElement()->GetText(), result );
  847. doc.Print();
  848. }
  849. {
  850. // Attribute values with trailing quotes not handled correctly
  851. XMLDocument doc;
  852. doc.Parse( "<foo attribute=bar\" />" );
  853. XMLTest( "Throw error with bad end quotes.", doc.Error(), true );
  854. }
  855. {
  856. // [ 1663758 ] Failure to report error on bad XML
  857. XMLDocument xml;
  858. xml.Parse("<x>");
  859. XMLTest("Missing end tag at end of input", xml.Error(), true);
  860. xml.Parse("<x> ");
  861. XMLTest("Missing end tag with trailing whitespace", xml.Error(), true);
  862. xml.Parse("<x></y>");
  863. XMLTest("Mismatched tags", xml.ErrorID(), XML_ERROR_MISMATCHED_ELEMENT);
  864. }
  865. {
  866. // [ 1475201 ] TinyXML parses entities in comments
  867. XMLDocument xml;
  868. xml.Parse("<!-- declarations for <head> & <body> -->"
  869. "<!-- far &amp; away -->" );
  870. XMLNode* e0 = xml.FirstChild();
  871. XMLNode* e1 = e0->NextSibling();
  872. XMLComment* c0 = e0->ToComment();
  873. XMLComment* c1 = e1->ToComment();
  874. XMLTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
  875. XMLTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
  876. }
  877. {
  878. XMLDocument xml;
  879. xml.Parse( "<Parent>"
  880. "<child1 att=''/>"
  881. "<!-- With this comment, child2 will not be parsed! -->"
  882. "<child2 att=''/>"
  883. "</Parent>" );
  884. xml.Print();
  885. int count = 0;
  886. for( XMLNode* ele = xml.FirstChildElement( "Parent" )->FirstChild();
  887. ele;
  888. ele = ele->NextSibling() )
  889. {
  890. ++count;
  891. }
  892. XMLTest( "Comments iterate correctly.", 3, count );
  893. }
  894. {
  895. // trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well.
  896. unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl";
  897. buf[60] = 239;
  898. buf[61] = 0;
  899. XMLDocument doc;
  900. doc.Parse( (const char*)buf);
  901. }
  902. {
  903. // bug 1827248 Error while parsing a little bit malformed file
  904. // Actually not malformed - should work.
  905. XMLDocument xml;
  906. xml.Parse( "<attributelist> </attributelist >" );
  907. XMLTest( "Handle end tag whitespace", false, xml.Error() );
  908. }
  909. {
  910. // This one must not result in an infinite loop
  911. XMLDocument xml;
  912. xml.Parse( "<infinite>loop" );
  913. XMLTest( "Infinite loop test.", true, true );
  914. }
  915. #endif
  916. {
  917. const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>";
  918. XMLDocument doc;
  919. doc.Parse( pub );
  920. XMLDocument clone;
  921. for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) {
  922. XMLNode* copy = node->ShallowClone( &clone );
  923. clone.InsertEndChild( copy );
  924. }
  925. clone.Print();
  926. int count=0;
  927. const XMLNode* a=clone.FirstChild();
  928. const XMLNode* b=doc.FirstChild();
  929. for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) {
  930. ++count;
  931. XMLTest( "Clone and Equal", true, a->ShallowEqual( b ));
  932. }
  933. XMLTest( "Clone and Equal", 4, count );
  934. }
  935. {
  936. // This shouldn't crash.
  937. XMLDocument doc;
  938. if(XML_SUCCESS != doc.LoadFile( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ))
  939. {
  940. doc.PrintError();
  941. }
  942. XMLTest( "Error in snprinf handling.", true, doc.Error() );
  943. }
  944. {
  945. // Attribute ordering.
  946. static const char* xml = "<element attrib1=\"1\" attrib2=\"2\" attrib3=\"3\" />";
  947. XMLDocument doc;
  948. doc.Parse( xml );
  949. XMLElement* ele = doc.FirstChildElement();
  950. const XMLAttribute* a = ele->FirstAttribute();
  951. XMLTest( "Attribute order", "1", a->Value() );
  952. a = a->Next();
  953. XMLTest( "Attribute order", "2", a->Value() );
  954. a = a->Next();
  955. XMLTest( "Attribute order", "3", a->Value() );
  956. XMLTest( "Attribute order", "attrib3", a->Name() );
  957. ele->DeleteAttribute( "attrib2" );
  958. a = ele->FirstAttribute();
  959. XMLTest( "Attribute order", "1", a->Value() );
  960. a = a->Next();
  961. XMLTest( "Attribute order", "3", a->Value() );
  962. ele->DeleteAttribute( "attrib1" );
  963. ele->DeleteAttribute( "attrib3" );
  964. XMLTest( "Attribute order (empty)", false, ele->FirstAttribute() ? true : false );
  965. }
  966. {
  967. // Make sure an attribute with a space in it succeeds.
  968. static const char* xml0 = "<element attribute1= \"Test Attribute\"/>";
  969. static const char* xml1 = "<element attribute1 =\"Test Attribute\"/>";
  970. static const char* xml2 = "<element attribute1 = \"Test Attribute\"/>";
  971. XMLDocument doc0;
  972. doc0.Parse( xml0 );
  973. XMLDocument doc1;
  974. doc1.Parse( xml1 );
  975. XMLDocument doc2;
  976. doc2.Parse( xml2 );
  977. XMLElement* ele = 0;
  978. ele = doc0.FirstChildElement();
  979. XMLTest( "Attribute with space #1", "Test Attribute", ele->Attribute( "attribute1" ) );
  980. ele = doc1.FirstChildElement();
  981. XMLTest( "Attribute with space #2", "Test Attribute", ele->Attribute( "attribute1" ) );
  982. ele = doc2.FirstChildElement();
  983. XMLTest( "Attribute with space #3", "Test Attribute", ele->Attribute( "attribute1" ) );
  984. }
  985. {
  986. // Make sure we don't go into an infinite loop.
  987. static const char* xml = "<doc><element attribute='attribute'/><element attribute='attribute'/></doc>";
  988. XMLDocument doc;
  989. doc.Parse( xml );
  990. XMLElement* ele0 = doc.FirstChildElement()->FirstChildElement();
  991. XMLElement* ele1 = ele0->NextSiblingElement();
  992. bool equal = ele0->ShallowEqual( ele1 );
  993. XMLTest( "Infinite loop in shallow equal.", true, equal );
  994. }
  995. // -------- Handles ------------
  996. {
  997. static const char* xml = "<element attrib='bar'><sub>Text</sub></element>";
  998. XMLDocument doc;
  999. doc.Parse( xml );
  1000. XMLElement* ele = XMLHandle( doc ).FirstChildElement( "element" ).FirstChild().ToElement();
  1001. XMLTest( "Handle, success, mutable", ele->Value(), "sub" );
  1002. XMLHandle docH( doc );
  1003. ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement();
  1004. XMLTest( "Handle, dne, mutable", false, ele != 0 );
  1005. }
  1006. {
  1007. static const char* xml = "<element attrib='bar'><sub>Text</sub></element>";
  1008. XMLDocument doc;
  1009. doc.Parse( xml );
  1010. XMLConstHandle docH( doc );
  1011. const XMLElement* ele = docH.FirstChildElement( "element" ).FirstChild().ToElement();
  1012. XMLTest( "Handle, success, const", ele->Value(), "sub" );
  1013. ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement();
  1014. XMLTest( "Handle, dne, const", false, ele != 0 );
  1015. }
  1016. {
  1017. // Default Declaration & BOM
  1018. XMLDocument doc;
  1019. doc.InsertEndChild( doc.NewDeclaration() );
  1020. doc.SetBOM( true );
  1021. XMLPrinter printer;
  1022. doc.Print( &printer );
  1023. static const char* result = "\xef\xbb\xbf<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
  1024. XMLTest( "BOM and default declaration", printer.CStr(), result, false );
  1025. XMLTest( "CStrSize", printer.CStrSize(), 42, false );
  1026. }
  1027. {
  1028. const char* xml = "<ipxml ws='1'><info bla=' /></ipxml>";
  1029. XMLDocument doc;
  1030. doc.Parse( xml );
  1031. XMLTest( "Ill formed XML", true, doc.Error() );
  1032. }
  1033. // QueryXYZText
  1034. {
  1035. const char* xml = "<point> <x>1.2</x> <y>1</y> <z>38</z> <valid>true</valid> </point>";
  1036. XMLDocument doc;
  1037. doc.Parse( xml );
  1038. const XMLElement* pointElement = doc.RootElement();
  1039. int intValue = 0;
  1040. unsigned unsignedValue = 0;
  1041. float floatValue = 0;
  1042. double doubleValue = 0;
  1043. bool boolValue = false;
  1044. pointElement->FirstChildElement( "y" )->QueryIntText( &intValue );
  1045. pointElement->FirstChildElement( "y" )->QueryUnsignedText( &unsignedValue );
  1046. pointElement->FirstChildElement( "x" )->QueryFloatText( &floatValue );
  1047. pointElement->FirstChildElement( "x" )->QueryDoubleText( &doubleValue );
  1048. pointElement->FirstChildElement( "valid" )->QueryBoolText( &boolValue );
  1049. XMLTest( "QueryIntText", intValue, 1, false );
  1050. XMLTest( "QueryUnsignedText", unsignedValue, (unsigned)1, false );
  1051. XMLTest( "QueryFloatText", floatValue, 1.2f, false );
  1052. XMLTest( "QueryDoubleText", doubleValue, 1.2, false );
  1053. XMLTest( "QueryBoolText", boolValue, true, false );
  1054. }
  1055. {
  1056. const char* xml = "<element><_sub/><:sub/><sub:sub/><sub-sub/></element>";
  1057. XMLDocument doc;
  1058. doc.Parse( xml );
  1059. XMLTest( "Non-alpha element lead letter parses.", doc.Error(), false );
  1060. }
  1061. {
  1062. const char* xml = "<element _attr1=\"foo\" :attr2=\"bar\"></element>";
  1063. XMLDocument doc;
  1064. doc.Parse( xml );
  1065. XMLTest("Non-alpha attribute lead character parses.", doc.Error(), false);
  1066. }
  1067. {
  1068. const char* xml = "<3lement></3lement>";
  1069. XMLDocument doc;
  1070. doc.Parse( xml );
  1071. XMLTest("Element names with lead digit fail to parse.", doc.Error(), true);
  1072. }
  1073. {
  1074. const char* xml = "<element/>WOA THIS ISN'T GOING TO PARSE";
  1075. XMLDocument doc;
  1076. doc.Parse( xml, 10 );
  1077. XMLTest( "Set length of incoming data", doc.Error(), false );
  1078. }
  1079. {
  1080. XMLDocument doc;
  1081. XMLTest( "Document is initially empty", doc.NoChildren(), true );
  1082. doc.Clear();
  1083. XMLTest( "Empty is empty after Clear()", doc.NoChildren(), true );
  1084. doc.LoadFile( "resources/dream.xml" );
  1085. XMLTest( "Document has something to Clear()", doc.NoChildren(), false );
  1086. doc.Clear();
  1087. XMLTest( "Document Clear()'s", doc.NoChildren(), true );
  1088. }
  1089. // ----------- Whitespace ------------
  1090. {
  1091. const char* xml = "<element>"
  1092. "<a> This \nis &apos; text &apos; </a>"
  1093. "<b> This is &apos; text &apos; \n</b>"
  1094. "<c>This is &apos; \n\n text &apos;</c>"
  1095. "</element>";
  1096. XMLDocument doc( true, COLLAPSE_WHITESPACE );
  1097. doc.Parse( xml );
  1098. const XMLElement* element = doc.FirstChildElement();
  1099. for( const XMLElement* parent = element->FirstChildElement();
  1100. parent;
  1101. parent = parent->NextSiblingElement() )
  1102. {
  1103. XMLTest( "Whitespace collapse", "This is ' text '", parent->GetText() );
  1104. }
  1105. }
  1106. #if 0
  1107. {
  1108. // Passes if assert doesn't fire.
  1109. XMLDocument xmlDoc;
  1110. xmlDoc.NewDeclaration();
  1111. xmlDoc.NewComment("Configuration file");
  1112. XMLElement *root = xmlDoc.NewElement("settings");
  1113. root->SetAttribute("version", 2);
  1114. }
  1115. #endif
  1116. {
  1117. const char* xml = "<element> </element>";
  1118. XMLDocument doc( true, COLLAPSE_WHITESPACE );
  1119. doc.Parse( xml );
  1120. XMLTest( "Whitespace all space", true, 0 == doc.FirstChildElement()->FirstChild() );
  1121. }
  1122. {
  1123. // An assert should not fire.
  1124. const char* xml = "<element/>";
  1125. XMLDocument doc;
  1126. doc.Parse( xml );
  1127. XMLElement* ele = doc.NewElement( "unused" ); // This will get cleaned up with the 'doc' going out of scope.
  1128. XMLTest( "Tracking unused elements", true, ele != 0, false );
  1129. }
  1130. {
  1131. const char* xml = "<parent><child>abc</child></parent>";
  1132. XMLDocument doc;
  1133. doc.Parse( xml );
  1134. XMLElement* ele = doc.FirstChildElement( "parent")->FirstChildElement( "child");
  1135. XMLPrinter printer;
  1136. ele->Accept( &printer );
  1137. XMLTest( "Printing of sub-element", "<child>abc</child>\n", printer.CStr(), false );
  1138. }
  1139. {
  1140. XMLDocument doc;
  1141. XMLError error = doc.LoadFile( "resources/empty.xml" );
  1142. XMLTest( "Loading an empty file", XML_ERROR_EMPTY_DOCUMENT, error );
  1143. XMLTest( "Loading an empty file and ErrorName as string", "XML_ERROR_EMPTY_DOCUMENT", doc.ErrorName() );
  1144. doc.PrintError();
  1145. }
  1146. {
  1147. // BOM preservation
  1148. static const char* xml_bom_preservation = "\xef\xbb\xbf<element/>\n";
  1149. {
  1150. XMLDocument doc;
  1151. XMLTest( "BOM preservation (parse)", XML_SUCCESS, doc.Parse( xml_bom_preservation ), false );
  1152. XMLPrinter printer;
  1153. doc.Print( &printer );
  1154. XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true );
  1155. doc.SaveFile( "resources/bomtest.xml" );
  1156. }
  1157. {
  1158. XMLDocument doc;
  1159. doc.LoadFile( "resources/bomtest.xml" );
  1160. XMLTest( "BOM preservation (load)", true, doc.HasBOM(), false );
  1161. XMLPrinter printer;
  1162. doc.Print( &printer );
  1163. XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true );
  1164. }
  1165. }
  1166. {
  1167. // Insertion with Removal
  1168. const char* xml = "<?xml version=\"1.0\" ?>"
  1169. "<root>"
  1170. "<one>"
  1171. "<subtree>"
  1172. "<elem>element 1</elem>text<!-- comment -->"
  1173. "</subtree>"
  1174. "</one>"
  1175. "<two/>"
  1176. "</root>";
  1177. const char* xmlInsideTwo = "<?xml version=\"1.0\" ?>"
  1178. "<root>"
  1179. "<one/>"
  1180. "<two>"
  1181. "<subtree>"
  1182. "<elem>element 1</elem>text<!-- comment -->"
  1183. "</subtree>"
  1184. "</two>"
  1185. "</root>";
  1186. const char* xmlAfterOne = "<?xml version=\"1.0\" ?>"
  1187. "<root>"
  1188. "<one/>"
  1189. "<subtree>"
  1190. "<elem>element 1</elem>text<!-- comment -->"
  1191. "</subtree>"
  1192. "<two/>"
  1193. "</root>";
  1194. const char* xmlAfterTwo = "<?xml version=\"1.0\" ?>"
  1195. "<root>"
  1196. "<one/>"
  1197. "<two/>"
  1198. "<subtree>"
  1199. "<elem>element 1</elem>text<!-- comment -->"
  1200. "</subtree>"
  1201. "</root>";
  1202. XMLDocument doc;
  1203. doc.Parse(xml);
  1204. XMLElement* subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
  1205. XMLElement* two = doc.RootElement()->FirstChildElement("two");
  1206. two->InsertFirstChild(subtree);
  1207. XMLPrinter printer1(0, true);
  1208. doc.Accept(&printer1);
  1209. XMLTest("Move node from within <one> to <two>", xmlInsideTwo, printer1.CStr());
  1210. doc.Parse(xml);
  1211. subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
  1212. two = doc.RootElement()->FirstChildElement("two");
  1213. doc.RootElement()->InsertAfterChild(two, subtree);
  1214. XMLPrinter printer2(0, true);
  1215. doc.Accept(&printer2);
  1216. XMLTest("Move node from within <one> after <two>", xmlAfterTwo, printer2.CStr(), false);
  1217. doc.Parse(xml);
  1218. XMLNode* one = doc.RootElement()->FirstChildElement("one");
  1219. subtree = one->FirstChildElement("subtree");
  1220. doc.RootElement()->InsertAfterChild(one, subtree);
  1221. XMLPrinter printer3(0, true);
  1222. doc.Accept(&printer3);
  1223. XMLTest("Move node from within <one> after <one>", xmlAfterOne, printer3.CStr(), false);
  1224. doc.Parse(xml);
  1225. subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
  1226. two = doc.RootElement()->FirstChildElement("two");
  1227. doc.RootElement()->InsertEndChild(subtree);
  1228. XMLPrinter printer4(0, true);
  1229. doc.Accept(&printer4);
  1230. XMLTest("Move node from within <one> after <two>", xmlAfterTwo, printer4.CStr(), false);
  1231. }
  1232. {
  1233. const char* xml = "<svg width = \"128\" height = \"128\">"
  1234. " <text> </text>"
  1235. "</svg>";
  1236. XMLDocument doc;
  1237. doc.Parse(xml);
  1238. doc.Print();
  1239. }
  1240. {
  1241. // Test that it doesn't crash.
  1242. const char* xml = "<?xml version=\"1.0\"?><root><sample><field0><1</field0><field1>2</field1></sample></root>";
  1243. XMLDocument doc;
  1244. doc.Parse(xml);
  1245. doc.PrintError();
  1246. }
  1247. #if 1
  1248. // the question being explored is what kind of print to use:
  1249. // https://github.com/leethomason/tinyxml2/issues/63
  1250. {
  1251. //const char* xml = "<element attrA='123456789.123456789' attrB='1.001e9' attrC='1.0e-10' attrD='1001000000.000000' attrE='0.1234567890123456789'/>";
  1252. const char* xml = "<element/>";
  1253. XMLDocument doc;
  1254. doc.Parse( xml );
  1255. doc.FirstChildElement()->SetAttribute( "attrA-f64", 123456789.123456789 );
  1256. doc.FirstChildElement()->SetAttribute( "attrB-f64", 1.001e9 );
  1257. doc.FirstChildElement()->SetAttribute( "attrC-f64", 1.0e9 );
  1258. doc.FirstChildElement()->SetAttribute( "attrC-f64", 1.0e20 );
  1259. doc.FirstChildElement()->SetAttribute( "attrD-f64", 1.0e-10 );
  1260. doc.FirstChildElement()->SetAttribute( "attrD-f64", 0.123456789 );
  1261. doc.FirstChildElement()->SetAttribute( "attrA-f32", 123456789.123456789f );
  1262. doc.FirstChildElement()->SetAttribute( "attrB-f32", 1.001e9f );
  1263. doc.FirstChildElement()->SetAttribute( "attrC-f32", 1.0e9f );
  1264. doc.FirstChildElement()->SetAttribute( "attrC-f32", 1.0e20f );
  1265. doc.FirstChildElement()->SetAttribute( "attrD-f32", 1.0e-10f );
  1266. doc.FirstChildElement()->SetAttribute( "attrD-f32", 0.123456789f );
  1267. doc.Print();
  1268. /* The result of this test is platform, compiler, and library version dependent. :("
  1269. XMLPrinter printer;
  1270. doc.Print( &printer );
  1271. XMLTest( "Float and double formatting.",
  1272. "<element attrA-f64=\"123456789.12345679\" attrB-f64=\"1001000000\" attrC-f64=\"1e+20\" attrD-f64=\"0.123456789\" attrA-f32=\"1.2345679e+08\" attrB-f32=\"1.001e+09\" attrC-f32=\"1e+20\" attrD-f32=\"0.12345679\"/>\n",
  1273. printer.CStr(),
  1274. true );
  1275. */
  1276. }
  1277. #endif
  1278. {
  1279. // Issue #184
  1280. // If it doesn't assert, it passes. Caused by objects
  1281. // getting created during parsing which are then
  1282. // inaccessible in the memory pools.
  1283. {
  1284. XMLDocument doc;
  1285. doc.Parse("<?xml version=\"1.0\" encoding=\"UTF-8\"?><test>");
  1286. }
  1287. {
  1288. XMLDocument doc;
  1289. doc.Parse("<?xml version=\"1.0\" encoding=\"UTF-8\"?><test>");
  1290. doc.Clear();
  1291. }
  1292. }
  1293. {
  1294. // If this doesn't assert in DEBUG, all is well.
  1295. tinyxml2::XMLDocument doc;
  1296. tinyxml2::XMLElement *pRoot = doc.NewElement("Root");
  1297. doc.DeleteNode(pRoot);
  1298. }
  1299. {
  1300. // Should not assert in DEBUG
  1301. XMLPrinter printer;
  1302. }
  1303. {
  1304. // Issue 291. Should not crash
  1305. const char* xml = "&#0</a>";
  1306. XMLDocument doc;
  1307. doc.Parse( xml );
  1308. XMLPrinter printer;
  1309. doc.Print( &printer );
  1310. }
  1311. {
  1312. // Issue 299. Can print elements that are not linked in.
  1313. // Will crash if issue not fixed.
  1314. XMLDocument doc;
  1315. XMLElement* newElement = doc.NewElement( "printme" );
  1316. XMLPrinter printer;
  1317. newElement->Accept( &printer );
  1318. // Delete the node to avoid possible memory leak report in debug output
  1319. doc.DeleteNode( newElement );
  1320. }
  1321. {
  1322. // Issue 302. Clear errors from LoadFile/SaveFile
  1323. XMLDocument doc;
  1324. XMLTest( "Issue 302. Should be no error initially", "XML_SUCCESS", doc.ErrorName() );
  1325. doc.SaveFile( "./no/such/path/pretty.xml" );
  1326. XMLTest( "Issue 302. Fail to save", "XML_ERROR_FILE_COULD_NOT_BE_OPENED", doc.ErrorName() );
  1327. doc.SaveFile( "./resources/out/compact.xml", true );
  1328. XMLTest( "Issue 302. Subsequent success in saving", "XML_SUCCESS", doc.ErrorName() );
  1329. }
  1330. {
  1331. // If a document fails to load then subsequent
  1332. // successful loads should clear the error
  1333. XMLDocument doc;
  1334. XMLTest( "Should be no error initially", false, doc.Error() );
  1335. doc.LoadFile( "resources/no-such-file.xml" );
  1336. XMLTest( "No such file - should fail", true, doc.Error() );
  1337. doc.LoadFile( "resources/dream.xml" );
  1338. XMLTest( "Error should be cleared", false, doc.Error() );
  1339. }
  1340. {
  1341. // Check that declarations are allowed only at beginning of document
  1342. const char* xml0 = "<?xml version=\"1.0\" ?>"
  1343. " <!-- xml version=\"1.1\" -->"
  1344. "<first />";
  1345. const char* xml1 = "<?xml version=\"1.0\" ?>"
  1346. "<?xml-stylesheet type=\"text/xsl\" href=\"Anything.xsl\"?>"
  1347. "<first />";
  1348. const char* xml2 = "<first />"
  1349. "<?xml version=\"1.0\" ?>";
  1350. const char* xml3 = "<first></first>"
  1351. "<?xml version=\"1.0\" ?>";
  1352. const char* xml4 = "<first><?xml version=\"1.0\" ?></first>";
  1353. XMLDocument doc;
  1354. doc.Parse(xml0);
  1355. XMLTest("Test that the code changes do not affect normal parsing", doc.Error(), false);
  1356. doc.Parse(xml1);
  1357. XMLTest("Test that the second declaration is allowed", doc.Error(), false);
  1358. doc.Parse(xml2);
  1359. XMLTest("Test that declaration after a child is not allowed", doc.ErrorID(), XML_ERROR_PARSING_DECLARATION);
  1360. doc.Parse(xml3);
  1361. XMLTest("Test that declaration after a child is not allowed", doc.ErrorID(), XML_ERROR_PARSING_DECLARATION);
  1362. doc.Parse(xml4);
  1363. XMLTest("Test that declaration inside a child is not allowed", doc.ErrorID(), XML_ERROR_PARSING_DECLARATION);
  1364. }
  1365. {
  1366. // No matter - before or after successfully parsing a text -
  1367. // calling XMLDocument::Value() causes an assert in debug.
  1368. const char* validXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
  1369. "<first />"
  1370. "<second />";
  1371. XMLDocument* doc = new XMLDocument();
  1372. XMLTest( "XMLDocument::Value() returns null?", NULL, doc->Value() );
  1373. doc->Parse( validXml );
  1374. XMLTest( "XMLDocument::Value() returns null?", NULL, doc->Value() );
  1375. delete doc;
  1376. }
  1377. {
  1378. XMLDocument doc;
  1379. for( int i = 0; i < XML_ERROR_COUNT; i++ ) {
  1380. doc.SetError( (XMLError)i, 0, 0 );
  1381. doc.ErrorName();
  1382. }
  1383. }
  1384. // ----------- Performance tracking --------------
  1385. {
  1386. #if defined( _MSC_VER )
  1387. __int64 start, end, freq;
  1388. QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
  1389. #endif
  1390. FILE* perfFP = fopen("resources/dream.xml", "r");
  1391. fseek(perfFP, 0, SEEK_END);
  1392. long size = ftell(perfFP);
  1393. fseek(perfFP, 0, SEEK_SET);
  1394. char* mem = new char[size + 1];
  1395. fread(mem, size, 1, perfFP);
  1396. fclose(perfFP);
  1397. mem[size] = 0;
  1398. #if defined( _MSC_VER )
  1399. QueryPerformanceCounter((LARGE_INTEGER*)&start);
  1400. #else
  1401. clock_t cstart = clock();
  1402. #endif
  1403. static const int COUNT = 10;
  1404. for (int i = 0; i < COUNT; ++i) {
  1405. XMLDocument doc;
  1406. doc.Parse(mem);
  1407. }
  1408. #if defined( _MSC_VER )
  1409. QueryPerformanceCounter((LARGE_INTEGER*)&end);
  1410. #else
  1411. clock_t cend = clock();
  1412. #endif
  1413. delete[] mem;
  1414. static const char* note =
  1415. #ifdef DEBUG
  1416. "DEBUG";
  1417. #else
  1418. "Release";
  1419. #endif
  1420. #if defined( _MSC_VER )
  1421. printf("\nParsing %s of dream.xml: %.3f milli-seconds\n", note, 1000.0 * (double)(end - start) / ((double)freq * (double)COUNT));
  1422. #else
  1423. printf("\nParsing %s of dream.xml: %.3f milli-seconds\n", note, (double)(cend - cstart) / (double)COUNT);
  1424. #endif
  1425. }
  1426. #if defined( _MSC_VER ) && defined( DEBUG )
  1427. _CrtMemCheckpoint( &endMemState );
  1428. _CrtMemState diffMemState;
  1429. _CrtMemDifference( &diffMemState, &startMemState, &endMemState );
  1430. _CrtMemDumpStatistics( &diffMemState );
  1431. #endif
  1432. printf ("\nPass %d, Fail %d\n", gPass, gFail);
  1433. return gFail;
  1434. }