xmltest.cpp 53 KB

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