tutorial0.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
  5. <title>TinyXml: TinyXML Tutorial</title>
  6. <link href="tabs.css" rel="stylesheet" type="text/css"/>
  7. <link href="doxygen.css" rel="stylesheet" type="text/css"/>
  8. </head>
  9. <body>
  10. <!-- Generated by Doxygen 1.6.2 -->
  11. <div class="navigation" id="top">
  12. <div class="tabs">
  13. <ul>
  14. <li><a href="index.html"><span>Main&nbsp;Page</span></a></li>
  15. <li class="current"><a href="pages.html"><span>Related&nbsp;Pages</span></a></li>
  16. <li><a href="annotated.html"><span>Classes</span></a></li>
  17. <li><a href="files.html"><span>Files</span></a></li>
  18. </ul>
  19. </div>
  20. <div class="navpath"><a class="el" href="index.html">index</a>
  21. </div>
  22. </div>
  23. <div class="contents">
  24. <h1><a class="anchor" id="tutorial0">TinyXML Tutorial </a></h1><h1>What is this? </h1>
  25. <p>This tutorial has a few tips and suggestions on how to use TinyXML effectively.</p>
  26. <p>I've also tried to include some C++ tips like how to convert strings to integers and vice versa. This isn't anything to do with TinyXML itself, but it may helpful for your project so I've put it in anyway.</p>
  27. <p>If you don't know basic C++ concepts this tutorial won't be useful. Likewise if you don't know what a DOM is, look elsewhere first.</p>
  28. <h1>Before we start </h1>
  29. <p>Some example XML datasets/files will be used.</p>
  30. <p>example1.xml:</p>
  31. <div class="fragment"><pre class="fragment">
  32. &lt;?xml version="1.0" ?&gt;
  33. &lt;Hello&gt;World&lt;/Hello&gt;
  34. </pre></div><p>example2.xml:</p>
  35. <div class="fragment"><pre class="fragment">
  36. &lt;?xml version="1.0" ?&gt;
  37. &lt;poetry&gt;
  38. &lt;verse&gt;
  39. Alas
  40. Great World
  41. Alas (again)
  42. &lt;/verse&gt;
  43. &lt;/poetry&gt;
  44. </pre></div><p>example3.xml:</p>
  45. <div class="fragment"><pre class="fragment">
  46. &lt;?xml version="1.0" ?&gt;
  47. &lt;shapes&gt;
  48. &lt;circle name="int-based" x="20" y="30" r="50" /&gt;
  49. &lt;point name="float-based" x="3.5" y="52.1" /&gt;
  50. &lt;/shapes&gt;
  51. </pre></div><p>example4.xml</p>
  52. <div class="fragment"><pre class="fragment">
  53. &lt;?xml version="1.0" ?&gt;
  54. &lt;MyApp&gt;
  55. &lt;!-- Settings for MyApp --&gt;
  56. &lt;Messages&gt;
  57. &lt;Welcome&gt;Welcome to MyApp&lt;/Welcome&gt;
  58. &lt;Farewell&gt;Thank you for using MyApp&lt;/Farewell&gt;
  59. &lt;/Messages&gt;
  60. &lt;Windows&gt;
  61. &lt;Window name="MainFrame" x="5" y="15" w="400" h="250" /&gt;
  62. &lt;/Windows&gt;
  63. &lt;Connection ip="192.168.0.1" timeout="123.456000" /&gt;
  64. &lt;/MyApp&gt;
  65. </pre></div><h1>Getting Started </h1>
  66. <h2>Load XML from a file </h2>
  67. <p>The simplest way to load a file into a TinyXML DOM is:</p>
  68. <div class="fragment"><pre class="fragment">
  69. TiXmlDocument doc( "demo.xml" );
  70. doc.LoadFile();
  71. </pre></div><p>A more real-world usage is shown below. This will load the file and display the contents to STDOUT:</p>
  72. <div class="fragment"><pre class="fragment">
  73. // load the named file and dump its structure to STDOUT
  74. void dump_to_stdout(const char* pFilename)
  75. {
  76. TiXmlDocument doc(pFilename);
  77. bool loadOkay = doc.LoadFile();
  78. if (loadOkay)
  79. {
  80. printf("\n%s:\n", pFilename);
  81. dump_to_stdout( &amp;doc ); // defined later in the tutorial
  82. }
  83. else
  84. {
  85. printf("Failed to load file \"%s\"\n", pFilename);
  86. }
  87. }
  88. </pre></div><p>A simple demonstration of this function is to use a main like this:</p>
  89. <div class="fragment"><pre class="fragment">
  90. int main(void)
  91. {
  92. dump_to_stdout("example1.xml");
  93. return 0;
  94. }
  95. </pre></div><p>Recall that Example 1 XML is:</p>
  96. <div class="fragment"><pre class="fragment">
  97. &lt;?xml version="1.0" ?&gt;
  98. &lt;Hello&gt;World&lt;/Hello&gt;
  99. </pre></div><p>Running the program with this XML will display this in the console/DOS window:</p>
  100. <div class="fragment"><pre class="fragment">
  101. DOCUMENT
  102. + DECLARATION
  103. + ELEMENT Hello
  104. + TEXT[World]
  105. </pre></div><p>The ``dump_to_stdout`` function is defined later in this tutorial and is useful if you want to understand recursive traversal of a DOM.</p>
  106. <h2>Building Documents Programatically </h2>
  107. <p>This is how to build Example 1 pragmatically:</p>
  108. <div class="fragment"><pre class="fragment">
  109. void build_simple_doc( )
  110. {
  111. // Make xml: &lt;?xml ..&gt;&lt;Hello&gt;World&lt;/Hello&gt;
  112. TiXmlDocument doc;
  113. TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" );
  114. TiXmlElement * element = new TiXmlElement( "Hello" );
  115. TiXmlText * text = new TiXmlText( "World" );
  116. element-&gt;LinkEndChild( text );
  117. doc.LinkEndChild( decl );
  118. doc.LinkEndChild( element );
  119. doc.SaveFile( "madeByHand.xml" );
  120. }
  121. </pre></div><p>This can be loaded and displayed on the console with:</p>
  122. <div class="fragment"><pre class="fragment">
  123. dump_to_stdout("madeByHand.xml"); // this func defined later in the tutorial
  124. </pre></div><p>and you'll see it is identical to Example 1:</p>
  125. <div class="fragment"><pre class="fragment">
  126. madeByHand.xml:
  127. Document
  128. + Declaration
  129. + Element [Hello]
  130. + Text: [World]
  131. </pre></div><p>This code produces exactly the same XML DOM but it shows a different ordering to node creation and linking:</p>
  132. <div class="fragment"><pre class="fragment">
  133. void write_simple_doc2( )
  134. {
  135. // same as write_simple_doc1 but add each node
  136. // as early as possible into the tree.
  137. TiXmlDocument doc;
  138. TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" );
  139. doc.LinkEndChild( decl );
  140. TiXmlElement * element = new TiXmlElement( "Hello" );
  141. doc.LinkEndChild( element );
  142. TiXmlText * text = new TiXmlText( "World" );
  143. element-&gt;LinkEndChild( text );
  144. doc.SaveFile( "madeByHand2.xml" );
  145. }
  146. </pre></div><p>Both of these produce the same XML, namely:</p>
  147. <div class="fragment"><pre class="fragment">
  148. &lt;?xml version="1.0" ?&gt;
  149. &lt;Hello&gt;World&lt;/Hello&gt;
  150. </pre></div><p>Or in structure form:</p>
  151. <div class="fragment"><pre class="fragment">
  152. DOCUMENT
  153. + DECLARATION
  154. + ELEMENT Hello
  155. + TEXT[World]
  156. </pre></div><h2>Attributes </h2>
  157. <p>Given an existing node, settings attributes is easy:</p>
  158. <div class="fragment"><pre class="fragment">
  159. window = new TiXmlElement( "Demo" );
  160. window-&gt;SetAttribute("name", "Circle");
  161. window-&gt;SetAttribute("x", 5);
  162. window-&gt;SetAttribute("y", 15);
  163. window-&gt;SetDoubleAttribute("radius", 3.14159);
  164. </pre></div><p>You can it also work with the <a class="el" href="classTiXmlAttribute.html" title="An attribute is a name-value pair.">TiXmlAttribute</a> objects if you want.</p>
  165. <p>The following code shows one way (not the only way) to get all attributes of an element, print the name and string value, and if the value can be converted to an integer or double, print that value too:</p>
  166. <div class="fragment"><pre class="fragment">
  167. // print all attributes of pElement.
  168. // returns the number of attributes printed
  169. int dump_attribs_to_stdout(TiXmlElement* pElement, unsigned int indent)
  170. {
  171. if ( !pElement ) return 0;
  172. TiXmlAttribute* pAttrib=pElement-&gt;FirstAttribute();
  173. int i=0;
  174. int ival;
  175. double dval;
  176. const char* pIndent=getIndent(indent);
  177. printf("\n");
  178. while (pAttrib)
  179. {
  180. printf( "%s%s: value=[%s]", pIndent, pAttrib-&gt;Name(), pAttrib-&gt;Value());
  181. if (pAttrib-&gt;QueryIntValue(&amp;ival)==TIXML_SUCCESS) printf( " int=%d", ival);
  182. if (pAttrib-&gt;QueryDoubleValue(&amp;dval)==TIXML_SUCCESS) printf( " d=%1.1f", dval);
  183. printf( "\n" );
  184. i++;
  185. pAttrib=pAttrib-&gt;Next();
  186. }
  187. return i;
  188. }
  189. </pre></div><h2>Writing a document to a file </h2>
  190. <p>Writing a pre-built DOM to a file is trivial:</p>
  191. <div class="fragment"><pre class="fragment">
  192. doc.SaveFile( saveFilename );
  193. </pre></div><p>Recall, for example, example 4:</p>
  194. <div class="fragment"><pre class="fragment">
  195. &lt;?xml version="1.0" ?&gt;
  196. &lt;MyApp&gt;
  197. &lt;!-- Settings for MyApp --&gt;
  198. &lt;Messages&gt;
  199. &lt;Welcome&gt;Welcome to MyApp&lt;/Welcome&gt;
  200. &lt;Farewell&gt;Thank you for using MyApp&lt;/Farewell&gt;
  201. &lt;/Messages&gt;
  202. &lt;Windows&gt;
  203. &lt;Window name="MainFrame" x="5" y="15" w="400" h="250" /&gt;
  204. &lt;/Windows&gt;
  205. &lt;Connection ip="192.168.0.1" timeout="123.456000" /&gt;
  206. &lt;/MyApp&gt;
  207. </pre></div><p>The following function builds this DOM and writes the file "appsettings.xml":</p>
  208. <div class="fragment"><pre class="fragment">
  209. void write_app_settings_doc( )
  210. {
  211. TiXmlDocument doc;
  212. TiXmlElement* msg;
  213. TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
  214. doc.LinkEndChild( decl );
  215. TiXmlElement * root = new TiXmlElement( "MyApp" );
  216. doc.LinkEndChild( root );
  217. TiXmlComment * comment = new TiXmlComment();
  218. comment-&gt;SetValue(" Settings for MyApp " );
  219. root-&gt;LinkEndChild( comment );
  220. TiXmlElement * msgs = new TiXmlElement( "Messages" );
  221. root-&gt;LinkEndChild( msgs );
  222. msg = new TiXmlElement( "Welcome" );
  223. msg-&gt;LinkEndChild( new TiXmlText( "Welcome to MyApp" ));
  224. msgs-&gt;LinkEndChild( msg );
  225. msg = new TiXmlElement( "Farewell" );
  226. msg-&gt;LinkEndChild( new TiXmlText( "Thank you for using MyApp" ));
  227. msgs-&gt;LinkEndChild( msg );
  228. TiXmlElement * windows = new TiXmlElement( "Windows" );
  229. root-&gt;LinkEndChild( windows );
  230. TiXmlElement * window;
  231. window = new TiXmlElement( "Window" );
  232. windows-&gt;LinkEndChild( window );
  233. window-&gt;SetAttribute("name", "MainFrame");
  234. window-&gt;SetAttribute("x", 5);
  235. window-&gt;SetAttribute("y", 15);
  236. window-&gt;SetAttribute("w", 400);
  237. window-&gt;SetAttribute("h", 250);
  238. TiXmlElement * cxn = new TiXmlElement( "Connection" );
  239. root-&gt;LinkEndChild( cxn );
  240. cxn-&gt;SetAttribute("ip", "192.168.0.1");
  241. cxn-&gt;SetDoubleAttribute("timeout", 123.456); // floating point attrib
  242. dump_to_stdout( &amp;doc );
  243. doc.SaveFile( "appsettings.xml" );
  244. }
  245. </pre></div><p>The dump_to_stdout function will show this structure:</p>
  246. <div class="fragment"><pre class="fragment">
  247. Document
  248. + Declaration
  249. + Element [MyApp]
  250. (No attributes)
  251. + Comment: [ Settings for MyApp ]
  252. + Element [Messages]
  253. (No attributes)
  254. + Element [Welcome]
  255. (No attributes)
  256. + Text: [Welcome to MyApp]
  257. + Element [Farewell]
  258. (No attributes)
  259. + Text: [Thank you for using MyApp]
  260. + Element [Windows]
  261. (No attributes)
  262. + Element [Window]
  263. + name: value=[MainFrame]
  264. + x: value=[5] int=5 d=5.0
  265. + y: value=[15] int=15 d=15.0
  266. + w: value=[400] int=400 d=400.0
  267. + h: value=[250] int=250 d=250.0
  268. 5 attributes
  269. + Element [Connection]
  270. + ip: value=[192.168.0.1] int=192 d=192.2
  271. + timeout: value=[123.456000] int=123 d=123.5
  272. 2 attributes
  273. </pre></div><p>I was surprised that TinyXml, by default, writes the XML in what other APIs call a "pretty" format - it modifies the whitespace of text of elements that contain other nodes so that writing the tree includes an indication of nesting level.</p>
  274. <p>I haven't looked yet to see if there is a way to turn off indenting when writing a file - its bound to be easy.</p>
  275. <p>[Lee: It's easy in STL mode, just use cout &lt;&lt; myDoc. Non-STL mode is always in "pretty" format. Adding a switch would be a nice feature and has been requested.]</p>
  276. <h1>XML to/from C++ objects </h1>
  277. <h2>Intro </h2>
  278. <p>This example assumes you're loading and saving your app settings in an XML file, e.g. something like example4.xml.</p>
  279. <p>There are a number of ways to do this. For example, look into the TinyBind project at <a href="http://sourceforge.net/projects/tinybind">http://sourceforge.net/projects/tinybind</a></p>
  280. <p>This section shows a plain-old approach to loading and saving a basic object structure using XML.</p>
  281. <h2>Set up your object classes </h2>
  282. <p>Start off with some basic classes like these:</p>
  283. <div class="fragment"><pre class="fragment">
  284. #include &lt;string&gt;
  285. #include &lt;map&gt;
  286. using namespace std;
  287. typedef std::map&lt;std::string,std::string&gt; MessageMap;
  288. // a basic window abstraction - demo purposes only
  289. class WindowSettings
  290. {
  291. public:
  292. int x,y,w,h;
  293. string name;
  294. WindowSettings()
  295. : x(0), y(0), w(100), h(100), name("Untitled")
  296. {
  297. }
  298. WindowSettings(int x, int y, int w, int h, const string&amp; name)
  299. {
  300. this-&gt;x=x;
  301. this-&gt;y=y;
  302. this-&gt;w=w;
  303. this-&gt;h=h;
  304. this-&gt;name=name;
  305. }
  306. };
  307. class ConnectionSettings
  308. {
  309. public:
  310. string ip;
  311. double timeout;
  312. };
  313. class AppSettings
  314. {
  315. public:
  316. string m_name;
  317. MessageMap m_messages;
  318. list&lt;WindowSettings&gt; m_windows;
  319. ConnectionSettings m_connection;
  320. AppSettings() {}
  321. void save(const char* pFilename);
  322. void load(const char* pFilename);
  323. // just to show how to do it
  324. void setDemoValues()
  325. {
  326. m_name="MyApp";
  327. m_messages.clear();
  328. m_messages["Welcome"]="Welcome to "+m_name;
  329. m_messages["Farewell"]="Thank you for using "+m_name;
  330. m_windows.clear();
  331. m_windows.push_back(WindowSettings(15,15,400,250,"Main"));
  332. m_connection.ip="Unknown";
  333. m_connection.timeout=123.456;
  334. }
  335. };
  336. </pre></div><p>This is a basic main() that shows how to create a default settings object tree, save it and load it again:</p>
  337. <div class="fragment"><pre class="fragment">
  338. int main(void)
  339. {
  340. AppSettings settings;
  341. settings.save("appsettings2.xml");
  342. settings.load("appsettings2.xml");
  343. return 0;
  344. }
  345. </pre></div><p>The following main() shows creation, modification, saving and then loading of a settings structure:</p>
  346. <div class="fragment"><pre class="fragment">
  347. int main(void)
  348. {
  349. // block: customise and save settings
  350. {
  351. AppSettings settings;
  352. settings.m_name="HitchHikerApp";
  353. settings.m_messages["Welcome"]="Don't Panic";
  354. settings.m_messages["Farewell"]="Thanks for all the fish";
  355. settings.m_windows.push_back(WindowSettings(15,25,300,250,"BookFrame"));
  356. settings.m_connection.ip="192.168.0.77";
  357. settings.m_connection.timeout=42.0;
  358. settings.save("appsettings2.xml");
  359. }
  360. // block: load settings
  361. {
  362. AppSettings settings;
  363. settings.load("appsettings2.xml");
  364. printf("%s: %s\n", settings.m_name.c_str(),
  365. settings.m_messages["Welcome"].c_str());
  366. WindowSettings &amp; w=settings.m_windows.front();
  367. printf("%s: Show window '%s' at %d,%d (%d x %d)\n",
  368. settings.m_name.c_str(), w.name.c_str(), w.x, w.y, w.w, w.h);
  369. printf("%s: %s\n", settings.m_name.c_str(), settings.m_messages["Farewell"].c_str());
  370. }
  371. return 0;
  372. }
  373. </pre></div><p>When the save() and load() are completed (see below), running this main() displays on the console:</p>
  374. <div class="fragment"><pre class="fragment">
  375. HitchHikerApp: Don't Panic
  376. HitchHikerApp: Show window 'BookFrame' at 15,25 (300 x 100)
  377. HitchHikerApp: Thanks for all the fish
  378. </pre></div><h2>Encode C++ state as XML </h2>
  379. <p>There are lots of different ways to approach saving this to a file. Here's one:</p>
  380. <div class="fragment"><pre class="fragment">
  381. void AppSettings::save(const char* pFilename)
  382. {
  383. TiXmlDocument doc;
  384. TiXmlElement* msg;
  385. TiXmlComment * comment;
  386. string s;
  387. TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
  388. doc.LinkEndChild( decl );
  389. TiXmlElement * root = new TiXmlElement(m_name.c_str());
  390. doc.LinkEndChild( root );
  391. comment = new TiXmlComment();
  392. s=" Settings for "+m_name+" ";
  393. comment-&gt;SetValue(s.c_str());
  394. root-&gt;LinkEndChild( comment );
  395. // block: messages
  396. {
  397. MessageMap::iterator iter;
  398. TiXmlElement * msgs = new TiXmlElement( "Messages" );
  399. root-&gt;LinkEndChild( msgs );
  400. for (iter=m_messages.begin(); iter != m_messages.end(); iter++)
  401. {
  402. const string &amp; key=(*iter).first;
  403. const string &amp; value=(*iter).second;
  404. msg = new TiXmlElement(key.c_str());
  405. msg-&gt;LinkEndChild( new TiXmlText(value.c_str()));
  406. msgs-&gt;LinkEndChild( msg );
  407. }
  408. }
  409. // block: windows
  410. {
  411. TiXmlElement * windowsNode = new TiXmlElement( "Windows" );
  412. root-&gt;LinkEndChild( windowsNode );
  413. list&lt;WindowSettings&gt;::iterator iter;
  414. for (iter=m_windows.begin(); iter != m_windows.end(); iter++)
  415. {
  416. const WindowSettings&amp; w=*iter;
  417. TiXmlElement * window;
  418. window = new TiXmlElement( "Window" );
  419. windowsNode-&gt;LinkEndChild( window );
  420. window-&gt;SetAttribute("name", w.name.c_str());
  421. window-&gt;SetAttribute("x", w.x);
  422. window-&gt;SetAttribute("y", w.y);
  423. window-&gt;SetAttribute("w", w.w);
  424. window-&gt;SetAttribute("h", w.h);
  425. }
  426. }
  427. // block: connection
  428. {
  429. TiXmlElement * cxn = new TiXmlElement( "Connection" );
  430. root-&gt;LinkEndChild( cxn );
  431. cxn-&gt;SetAttribute("ip", m_connection.ip.c_str());
  432. cxn-&gt;SetDoubleAttribute("timeout", m_connection.timeout);
  433. }
  434. doc.SaveFile(pFilename);
  435. }
  436. </pre></div><p>Running this with the modified main produces this file:</p>
  437. <div class="fragment"><pre class="fragment">
  438. &lt;?xml version="1.0" ?&gt;
  439. &lt;HitchHikerApp&gt;
  440. &lt;!-- Settings for HitchHikerApp --&gt;
  441. &lt;Messages&gt;
  442. &lt;Farewell&gt;Thanks for all the fish&lt;/Farewell&gt;
  443. &lt;Welcome&gt;Don&amp;apos;t Panic&lt;/Welcome&gt;
  444. &lt;/Messages&gt;
  445. &lt;Windows&gt;
  446. &lt;Window name="BookFrame" x="15" y="25" w="300" h="250" /&gt;
  447. &lt;/Windows&gt;
  448. &lt;Connection ip="192.168.0.77" timeout="42.000000" /&gt;
  449. &lt;/HitchHikerApp&gt;
  450. </pre></div><h2>Decoding state from XML </h2>
  451. <p>As with encoding objects, there are a number of approaches to decoding XML into your own C++ object structure. The following approach uses TiXmlHandles.</p>
  452. <div class="fragment"><pre class="fragment">
  453. void AppSettings::load(const char* pFilename)
  454. {
  455. TiXmlDocument doc(pFilename);
  456. if (!doc.LoadFile()) return;
  457. TiXmlHandle hDoc(&amp;doc);
  458. TiXmlElement* pElem;
  459. TiXmlHandle hRoot(0);
  460. // block: name
  461. {
  462. pElem=hDoc.FirstChildElement().Element();
  463. // should always have a valid root but handle gracefully if it does
  464. if (!pElem) return;
  465. m_name=pElem-&gt;Value();
  466. // save this for later
  467. hRoot=TiXmlHandle(pElem);
  468. }
  469. // block: string table
  470. {
  471. m_messages.clear(); // trash existing table
  472. pElem=hRoot.FirstChild( "Messages" ).FirstChild().Element();
  473. for( pElem; pElem; pElem=pElem-&gt;NextSiblingElement())
  474. {
  475. const char *pKey=pElem-&gt;Value();
  476. const char *pText=pElem-&gt;GetText();
  477. if (pKey &amp;&amp; pText)
  478. {
  479. m_messages[pKey]=pText;
  480. }
  481. }
  482. }
  483. // block: windows
  484. {
  485. m_windows.clear(); // trash existing list
  486. TiXmlElement* pWindowNode=hRoot.FirstChild( "Windows" ).FirstChild().Element();
  487. for( pWindowNode; pWindowNode; pWindowNode=pWindowNode-&gt;NextSiblingElement())
  488. {
  489. WindowSettings w;
  490. const char *pName=pWindowNode-&gt;Attribute("name");
  491. if (pName) w.name=pName;
  492. pWindowNode-&gt;QueryIntAttribute("x", &amp;w.x); // If this fails, original value is left as-is
  493. pWindowNode-&gt;QueryIntAttribute("y", &amp;w.y);
  494. pWindowNode-&gt;QueryIntAttribute("w", &amp;w.w);
  495. pWindowNode-&gt;QueryIntAttribute("hh", &amp;w.h);
  496. m_windows.push_back(w);
  497. }
  498. }
  499. // block: connection
  500. {
  501. pElem=hRoot.FirstChild("Connection").Element();
  502. if (pElem)
  503. {
  504. m_connection.ip=pElem-&gt;Attribute("ip");
  505. pElem-&gt;QueryDoubleAttribute("timeout",&amp;m_connection.timeout);
  506. }
  507. }
  508. }
  509. </pre></div><h1>Full listing for dump_to_stdout </h1>
  510. <p>Below is a copy-and-paste demo program for loading arbitrary XML files and dumping the structure to STDOUT using the recursive traversal listed above.</p>
  511. <div class="fragment"><pre class="fragment">
  512. // tutorial demo program
  513. #include "stdafx.h"
  514. #include "tinyxml.h"
  515. // ----------------------------------------------------------------------
  516. // STDOUT dump and indenting utility functions
  517. // ----------------------------------------------------------------------
  518. const unsigned int NUM_INDENTS_PER_SPACE=2;
  519. const char * getIndent( unsigned int numIndents )
  520. {
  521. static const char * pINDENT=" + ";
  522. static const unsigned int LENGTH=strlen( pINDENT );
  523. unsigned int n=numIndents*NUM_INDENTS_PER_SPACE;
  524. if ( n &gt; LENGTH ) n = LENGTH;
  525. return &amp;pINDENT[ LENGTH-n ];
  526. }
  527. // same as getIndent but no "+" at the end
  528. const char * getIndentAlt( unsigned int numIndents )
  529. {
  530. static const char * pINDENT=" ";
  531. static const unsigned int LENGTH=strlen( pINDENT );
  532. unsigned int n=numIndents*NUM_INDENTS_PER_SPACE;
  533. if ( n &gt; LENGTH ) n = LENGTH;
  534. return &amp;pINDENT[ LENGTH-n ];
  535. }
  536. int dump_attribs_to_stdout(TiXmlElement* pElement, unsigned int indent)
  537. {
  538. if ( !pElement ) return 0;
  539. TiXmlAttribute* pAttrib=pElement-&gt;FirstAttribute();
  540. int i=0;
  541. int ival;
  542. double dval;
  543. const char* pIndent=getIndent(indent);
  544. printf("\n");
  545. while (pAttrib)
  546. {
  547. printf( "%s%s: value=[%s]", pIndent, pAttrib-&gt;Name(), pAttrib-&gt;Value());
  548. if (pAttrib-&gt;QueryIntValue(&amp;ival)==TIXML_SUCCESS) printf( " int=%d", ival);
  549. if (pAttrib-&gt;QueryDoubleValue(&amp;dval)==TIXML_SUCCESS) printf( " d=%1.1f", dval);
  550. printf( "\n" );
  551. i++;
  552. pAttrib=pAttrib-&gt;Next();
  553. }
  554. return i;
  555. }
  556. void dump_to_stdout( TiXmlNode* pParent, unsigned int indent = 0 )
  557. {
  558. if ( !pParent ) return;
  559. TiXmlNode* pChild;
  560. TiXmlText* pText;
  561. int t = pParent-&gt;Type();
  562. printf( "%s", getIndent(indent));
  563. int num;
  564. switch ( t )
  565. {
  566. case TiXmlNode::TINYXML_DOCUMENT:
  567. printf( "Document" );
  568. break;
  569. case TiXmlNode::TINYXML_ELEMENT:
  570. printf( "Element [%s]", pParent-&gt;Value() );
  571. num=dump_attribs_to_stdout(pParent-&gt;ToElement(), indent+1);
  572. switch(num)
  573. {
  574. case 0: printf( " (No attributes)"); break;
  575. case 1: printf( "%s1 attribute", getIndentAlt(indent)); break;
  576. default: printf( "%s%d attributes", getIndentAlt(indent), num); break;
  577. }
  578. break;
  579. case TiXmlNode::TINYXML_COMMENT:
  580. printf( "Comment: [%s]", pParent-&gt;Value());
  581. break;
  582. case TiXmlNode::TINYXML_UNKNOWN:
  583. printf( "Unknown" );
  584. break;
  585. case TiXmlNode::TINYXML_TEXT:
  586. pText = pParent-&gt;ToText();
  587. printf( "Text: [%s]", pText-&gt;Value() );
  588. break;
  589. case TiXmlNode::TINYXML_DECLARATION:
  590. printf( "Declaration" );
  591. break;
  592. default:
  593. break;
  594. }
  595. printf( "\n" );
  596. for ( pChild = pParent-&gt;FirstChild(); pChild != 0; pChild = pChild-&gt;NextSibling())
  597. {
  598. dump_to_stdout( pChild, indent+1 );
  599. }
  600. }
  601. // load the named file and dump its structure to STDOUT
  602. void dump_to_stdout(const char* pFilename)
  603. {
  604. TiXmlDocument doc(pFilename);
  605. bool loadOkay = doc.LoadFile();
  606. if (loadOkay)
  607. {
  608. printf("\n%s:\n", pFilename);
  609. dump_to_stdout( &amp;doc ); // defined later in the tutorial
  610. }
  611. else
  612. {
  613. printf("Failed to load file \"%s\"\n", pFilename);
  614. }
  615. }
  616. // ----------------------------------------------------------------------
  617. // main() for printing files named on the command line
  618. // ----------------------------------------------------------------------
  619. int main(int argc, char* argv[])
  620. {
  621. for (int i=1; i&lt;argc; i++)
  622. {
  623. dump_to_stdout(argv[i]);
  624. }
  625. return 0;
  626. }
  627. </pre></div><p>Run this from the command line or a DOS window, e.g.:</p>
  628. <div class="fragment"><pre class="fragment">
  629. C:\dev\tinyxml&gt; Debug\tinyxml_1.exe example1.xml
  630. example1.xml:
  631. Document
  632. + Declaration
  633. + Element [Hello]
  634. (No attributes)
  635. + Text: [World]
  636. </pre></div><p><em> Authors and Changes </p>
  637. <ul>
  638. <li>
  639. Written by Ellers, April, May, June 2005 </li>
  640. <li>
  641. Minor edits and integration into doc system, Lee Thomason September 2005 </li>
  642. <li>
  643. Updated by Ellers, October 2005 </li>
  644. </ul>
  645. <p></em> </p>
  646. </div>
  647. <hr size="1"/><address style="text-align: right;"><small>Generated by&nbsp;
  648. <a href="http://www.doxygen.org/index.html">
  649. <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.2 </small></address>
  650. </body>
  651. </html>