advanced.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. <html>
  2. <body>
  3. <h1 align='right'><a name='ADVANCED'><img src="3.gif" align="right"
  4. hspace="10" width="100" height="100" alt="3"></a>More Mini-XML
  5. Programming Techniques</h1>
  6. <p>This chapter shows additional ways to use the Mini-XML
  7. library in your programs.</p>
  8. <h2><a name='LOAD_CALLBACKS'>Load Callbacks</a></h2>
  9. <p><a href='#LOAD_XML'>Chapter 2</a> introduced the <a
  10. href='#mxmlLoadFile'><tt>mxmlLoadFile()</tt></a> and <a
  11. href='#mxmlLoadString'><tt>mxmlLoadString()</tt></a> functions.
  12. The last argument to these functions is a callback function
  13. which is used to determine the value type of each data node in
  14. an XML document.</p>
  15. <p>Mini-XML defines several standard callbacks for simple
  16. XML data files:</p>
  17. <ul>
  18. <li><tt>MXML_INTEGER_CALLBACK</tt> - All data nodes
  19. contain whitespace-separated integers.</li>
  20. <li><tt>MXML_OPAQUE_CALLBACK</tt> - All data nodes
  21. contain opaque strings ("CDATA").</li>
  22. <li><tt>MXML_REAL_CALLBACK</tt> - All data nodes contain
  23. whitespace-separated floating-point numbers.</li>
  24. <li><tt>MXML_TEXT_CALLBACK</tt> - All data nodes contain
  25. whitespace-separated strings.</li>
  26. </ul>
  27. <p>You can provide your own callback functions for more complex
  28. XML documents. Your callback function will receive a pointer to
  29. the current element node and must return the value type of the
  30. immediate children for that element node: <tt>MXML_INTEGER</tt>,
  31. <tt>MXML_OPAQUE</tt>, <tt>MXML_REAL</tt>, or <tt>MXML_TEXT</tt>.
  32. The function is called <i>after</i> the element and its
  33. attributes have been read, so you can look at the element name,
  34. attributes, and attribute values to determine the proper value
  35. type to return.</p>
  36. <!-- NEED 2in -->
  37. <p>The following callback function looks for an attribute named
  38. "type" or the element name to determine the value type for its
  39. child nodes:</p>
  40. <pre>
  41. mxml_type_t
  42. type_cb(mxml_node_t *node)
  43. {
  44. const char *type;
  45. /*
  46. * You can lookup attributes and/or use the
  47. * element name, hierarchy, etc...
  48. */
  49. type = mxmlElementGetAttr(node, "type");
  50. if (type == NULL)
  51. type = mxmlGetElement(node);
  52. if (!strcmp(type, "integer"))
  53. return (MXML_INTEGER);
  54. else if (!strcmp(type, "opaque"))
  55. return (MXML_OPAQUE);
  56. else if (!strcmp(type, "real"))
  57. return (MXML_REAL);
  58. else
  59. return (MXML_TEXT);
  60. }
  61. </pre>
  62. <p>To use this callback function, simply use the name when you
  63. call any of the load functions:</p>
  64. <pre>
  65. FILE *fp;
  66. mxml_node_t *tree;
  67. fp = fopen("filename.xml", "r");
  68. tree = mxmlLoadFile(NULL, fp, <b>type_cb</b>);
  69. fclose(fp);
  70. </pre>
  71. <h2><a name='SAVE_CALLBACKS'>Save Callbacks</a></h2>
  72. <p><a href='#LOAD_XML'>Chapter 2</a> also introduced the <a
  73. href='#mxmlSaveFile'><tt>mxmlSaveFile()</tt></a>, <a
  74. href='#mxmlSaveString'><tt>mxmlSaveString()</tt></a>, and <a
  75. href='#mxmlSaveAllocString'><tt>mxmlSaveAllocString()</tt></a>
  76. functions. The last argument to these functions is a callback
  77. function which is used to automatically insert whitespace in an
  78. XML document.</p>
  79. <p>Your callback function will be called up to four times for
  80. each element node with a pointer to the node and a "where" value
  81. of <tt>MXML_WS_BEFORE_OPEN</tt>, <tt>MXML_WS_AFTER_OPEN</tt>,
  82. <tt>MXML_WS_BEFORE_CLOSE</tt>, or <tt>MXML_WS_AFTER_CLOSE</tt>.
  83. The callback function should return <tt>NULL</tt> if no
  84. whitespace should be added and the string to insert (spaces,
  85. tabs, carriage returns, and newlines) otherwise.</p>
  86. <p>The following whitespace callback can be used to add
  87. whitespace to XHTML output to make it more readable in a standard
  88. text editor:</p>
  89. <pre>
  90. const char *
  91. whitespace_cb(mxml_node_t *node,
  92. int where)
  93. {
  94. const char *name;
  95. /*
  96. * We can conditionally break to a new line
  97. * before or after any element. These are
  98. * just common HTML elements...
  99. */
  100. name = mxmlGetElement(node);
  101. if (!strcmp(name, "html") ||
  102. !strcmp(name, "head") ||
  103. !strcmp(name, "body") ||
  104. !strcmp(name, "pre") ||
  105. !strcmp(name, "p") ||
  106. !strcmp(name, "h1") ||
  107. !strcmp(name, "h2") ||
  108. !strcmp(name, "h3") ||
  109. !strcmp(name, "h4") ||
  110. !strcmp(name, "h5") ||
  111. !strcmp(name, "h6"))
  112. {
  113. /*
  114. * Newlines before open and after
  115. * close...
  116. */
  117. if (where == MXML_WS_BEFORE_OPEN ||
  118. where == MXML_WS_AFTER_CLOSE)
  119. return ("\n");
  120. }
  121. else if (!strcmp(name, "dl") ||
  122. !strcmp(name, "ol") ||
  123. !strcmp(name, "ul"))
  124. {
  125. /*
  126. * Put a newline before and after list
  127. * elements...
  128. */
  129. return ("\n");
  130. }
  131. else if (!strcmp(name, "dd") ||
  132. !strcmp(name, "dt") ||
  133. !strcmp(name, "li"))
  134. {
  135. /*
  136. * Put a tab before &lt;li>'s, * &lt;dd>'s,
  137. * and &lt;dt>'s, and a newline after them...
  138. */
  139. if (where == MXML_WS_BEFORE_OPEN)
  140. return ("\t");
  141. else if (where == MXML_WS_AFTER_CLOSE)
  142. return ("\n");
  143. }
  144. /*
  145. * Return NULL for no added whitespace...
  146. */
  147. return (NULL);
  148. }
  149. </pre>
  150. <p>To use this callback function, simply use the name when you
  151. call any of the save functions:</p>
  152. <pre>
  153. FILE *fp;
  154. mxml_node_t *tree;
  155. fp = fopen("filename.xml", "w");
  156. mxmlSaveFile(tree, fp, <b>whitespace_cb</b>);
  157. fclose(fp);
  158. </pre>
  159. <!-- NEED 10 -->
  160. <h2>Custom Data Types</h2>
  161. <p>Mini-XML supports custom data types via global load and save
  162. callbacks. Only a single set of callbacks can be active at any
  163. time, however your callbacks can store additional information in
  164. order to support multiple custom data types as needed. The
  165. <tt>MXML_CUSTOM</tt> node type identifies custom data nodes.</p>
  166. <p>The load callback receives a pointer to the current data node
  167. and a string of opaque character data from the XML source with
  168. character entities converted to the corresponding UTF-8
  169. characters. For example, if we wanted to support a custom
  170. date/time type whose value is encoded as "yyyy-mm-ddThh:mm:ssZ"
  171. (ISO format), the load callback would look like the
  172. following:</p>
  173. <pre>
  174. typedef struct
  175. {
  176. unsigned year, /* Year */
  177. month, /* Month */
  178. day, /* Day */
  179. hour, /* Hour */
  180. minute, /* Minute */
  181. second; /* Second */
  182. time_t unix; /* UNIX time */
  183. } iso_date_time_t;
  184. int
  185. load_custom(mxml_node_t *node,
  186. const char *data)
  187. {
  188. iso_date_time_t *dt;
  189. struct tm tmdata;
  190. /*
  191. * Allocate data structure...
  192. */
  193. dt = calloc(1, sizeof(iso_date_time_t));
  194. /*
  195. * Try reading 6 unsigned integers from the
  196. * data string...
  197. */
  198. if (sscanf(data, "%u-%u-%uT%u:%u:%uZ",
  199. &amp;(dt->year), &amp;(dt->month),
  200. &amp;(dt->day), &amp;(dt->hour),
  201. &amp;(dt->minute),
  202. &amp;(dt->second)) != 6)
  203. {
  204. /*
  205. * Unable to read numbers, free the data
  206. * structure and return an error...
  207. */
  208. free(dt);
  209. return (-1);
  210. }
  211. /*
  212. * Range check values...
  213. */
  214. if (dt->month < 1 || dt->month > 12 ||
  215. dt->day < 1 || dt->day > 31 ||
  216. dt->hour < 0 || dt->hour > 23 ||
  217. dt->minute < 0 || dt->minute > 59 ||
  218. dt->second < 0 || dt->second > 59)
  219. {
  220. /*
  221. * Date information is out of range...
  222. */
  223. free(dt);
  224. return (-1);
  225. }
  226. /*
  227. * Convert ISO time to UNIX time in
  228. * seconds...
  229. */
  230. tmdata.tm_year = dt->year - 1900;
  231. tmdata.tm_mon = dt->month - 1;
  232. tmdata.tm_day = dt->day;
  233. tmdata.tm_hour = dt->hour;
  234. tmdata.tm_min = dt->minute;
  235. tmdata.tm_sec = dt->second;
  236. dt->unix = gmtime(&amp;tmdata);
  237. /*
  238. * Assign custom node data and destroy
  239. * function pointers...
  240. */
  241. mxmlSetCustom(node, data, destroy);
  242. /*
  243. * Return with no errors...
  244. */
  245. return (0);
  246. }
  247. </pre>
  248. <p>The function itself can return 0 on success or -1 if it is
  249. unable to decode the custom data or the data contains an error.
  250. Custom data nodes contain a <tt>void</tt> pointer to the
  251. allocated custom data for the node and a pointer to a destructor
  252. function which will free the custom data when the node is
  253. deleted.</p>
  254. <!-- NEED 15 -->
  255. <p>The save callback receives the node pointer and returns an
  256. allocated string containing the custom data value. The following
  257. save callback could be used for our ISO date/time type:</p>
  258. <pre>
  259. char *
  260. save_custom(mxml_node_t *node)
  261. {
  262. char data[255];
  263. iso_date_time_t *dt;
  264. dt = (iso_date_time_t *)mxmlGetCustom(node);
  265. snprintf(data, sizeof(data),
  266. "%04u-%02u-%02uT%02u:%02u:%02uZ",
  267. dt->year, dt->month, dt->day,
  268. dt->hour, dt->minute, dt->second);
  269. return (strdup(data));
  270. }
  271. </pre>
  272. <p>You register the callback functions using the <a
  273. href='#mxmlSetCustomHandlers'><tt>mxmlSetCustomHandlers()</tt></a>
  274. function:</p>
  275. <pre>
  276. mxmlSetCustomHandlers(<b>load_custom</b>,
  277. <b>save_custom</b>);
  278. </pre>
  279. <!-- NEED 20 -->
  280. <h2>Changing Node Values</h2>
  281. <p>All of the examples so far have concentrated on creating and
  282. loading new XML data nodes. Many applications, however, need to
  283. manipulate or change the nodes during their operation, so
  284. Mini-XML provides functions to change node values safely and
  285. without leaking memory.</p>
  286. <p>Existing nodes can be changed using the <a
  287. href='#mxmlSetElement'><tt>mxmlSetElement()</tt></a>, <a
  288. href='#mxmlSetInteger'><tt>mxmlSetInteger()</tt></a>, <a
  289. href='#mxmlSetOpaque'><tt>mxmlSetOpaque()</tt></a>, <a
  290. href='#mxmlSetReal'><tt>mxmlSetReal()</tt></a>, <a
  291. href='#mxmlSetText'><tt>mxmlSetText()</tt></a>, and <a
  292. href='#mxmlSetTextf'><tt>mxmlSetTextf()</tt></a> functions. For
  293. example, use the following function call to change a text node
  294. to contain the text "new" with leading whitespace:</p>
  295. <pre>
  296. mxml_node_t *node;
  297. mxmlSetText(node, 1, "new");
  298. </pre>
  299. <h2>Formatted Text</h2>
  300. <p>The <a href='#mxmlNewTextf'><tt>mxmlNewTextf()</tt></a> and <a
  301. href='#mxmlSetTextf'><tt>mxmlSetTextf()</tt></a> functions create
  302. and change text nodes, respectively, using <tt>printf</tt>-style
  303. format strings and arguments. For example, use the following
  304. function call to create a new text node containing a constructed
  305. filename:</p>
  306. <pre>
  307. mxml_node_t</a> *node;
  308. node = mxmlNewTextf(node, 1, "%s/%s",
  309. path, filename);
  310. </pre>
  311. <h2>Indexing</h2>
  312. <p>Mini-XML provides functions for managing indices of nodes.
  313. The current implementation provides the same functionality as
  314. <a href='#mxmlFindElement'><tt>mxmlFindElement()</tt></a>.
  315. The advantage of using an index is that searching and
  316. enumeration of elements is significantly faster. The only
  317. disadvantage is that each index is a static snapshot of the XML
  318. document, so indices are not well suited to XML data that is
  319. updated more often than it is searched. The overhead of creating
  320. an index is approximately equal to walking the XML document
  321. tree. Nodes in the index are sorted by element name and
  322. attribute value.</p>
  323. <p>Indices are stored in <a href='#mxml_index_t'><tt>mxml_index_t</tt></a>
  324. structures. The <a href='#mxmlIndexNew'><tt>mxmlIndexNew()</tt></a> function
  325. creates a new index:</p>
  326. <pre>
  327. mxml_node_t *tree;
  328. mxml_index_t *ind;
  329. ind = mxmlIndexNew(tree, "element",
  330. "attribute");
  331. </pre>
  332. <p>The first argument is the XML node tree to index. Normally this
  333. will be a pointer to the <tt>?xml</tt> element.</p>
  334. <p>The second argument contains the element to index; passing
  335. <tt>NULL</tt> indexes all element nodes alphabetically.</p>
  336. <p>The third argument contains the attribute to index; passing
  337. <tt>NULL</tt> causes only the element name to be indexed.</p>
  338. <p>Once the index is created, the <a
  339. href='#mxmlIndexEnum'><tt>mxmlIndexEnum()</tt></a>, <a
  340. href='#mxmlIndexFind'><tt>mxmlIndexFind()</tt></a>, and <a
  341. href='#mxmlIndexReset'><tt>mxmlIndexReset()</tt></a> functions
  342. are used to access the nodes in the index. The <a
  343. href='#mxmlIndexReset'><tt>mxmlIndexReset()</tt></a> function
  344. resets the "current" node pointer in the index, allowing you to
  345. do new searches and enumerations on the same index. Typically
  346. you will call this function prior to your calls to <a
  347. href='#mxmlIndexEnum'><tt>mxmlIndexEnum()</tt></a> and <a
  348. href='#mxmlIndexFind'><tt>mxmlIndexFind()</tt></a>.</p>
  349. <p>The <a href='#mxmlIndexEnum'><tt>mxmlIndexEnum()</tt></a>
  350. function enumerates each of the nodes in the index and can be
  351. used in a loop as follows:</p>
  352. <pre>
  353. mxml_node_t *node;
  354. mxmlIndexReset(ind);
  355. while ((node = mxmlIndexEnum(ind)) != NULL)
  356. {
  357. // do something with node
  358. }
  359. </pre>
  360. <p>The <a href='#mxmlIndexFind'><tt>mxmlIndexFind()</tt></a>
  361. function locates the next occurrence of the named element and
  362. attribute value in the index. It can be used to find all
  363. matching elements in an index, as follows:</p>
  364. <pre>
  365. mxml_node_t *node;
  366. mxmlIndexReset(ind);
  367. while ((node = mxmlIndexFind(ind, "element",
  368. "attr-value"))
  369. != NULL)
  370. {
  371. // do something with node
  372. }
  373. </pre>
  374. <p>The second and third arguments represent the element name and
  375. attribute value, respectively. A <tt>NULL</tt> pointer is used
  376. to return all elements or attributes in the index. Passing
  377. <tt>NULL</tt> for both the element name and attribute value
  378. is equivalent to calling <tt>mxmlIndexEnum</tt>.</p>
  379. <p>When you are done using the index, delete it using the
  380. <a href='#mxmlIndexDelete()'><tt>mxmlIndexDelete()</tt></a>
  381. function:</p>
  382. <pre>
  383. mxmlIndexDelete(ind);
  384. </pre>
  385. <h2>SAX (Stream) Loading of Documents</h2>
  386. <p>Mini-XML supports an implementation of the Simple API for XML
  387. (SAX) which allows you to load and process an XML document as a
  388. stream of nodes. Aside from allowing you to process XML documents of
  389. any size, the Mini-XML implementation also allows you to retain
  390. portions of the document in memory for later processing.</p>
  391. <p>The <a href='#mxmlSAXLoad'><tt>mxmlSAXLoadFd</tt></a>, <a
  392. href='#mxmlSAXLoadFile'><tt>mxmlSAXLoadFile</tt></a>, and <a
  393. href='#mxmlSAXLoadString'><tt>mxmlSAXLoadString</tt></a> functions
  394. provide the SAX loading APIs. Each function works like the
  395. corresponding <tt>mxmlLoad</tt> function but uses a callback to
  396. process each node as it is read.</p>
  397. <p>The callback function receives the node, an event code, and
  398. a user data pointer you supply:</p>
  399. <pre>
  400. void
  401. sax_cb(mxml_node_t *node,
  402. mxml_sax_event_t event,
  403. void *data)
  404. {
  405. ... do something ...
  406. }
  407. </pre>
  408. <p>The event will be one of the following:</p>
  409. <ul>
  410. <li><tt>MXML_SAX_CDATA</tt> - CDATA was just read</li>
  411. <li><tt>MXML_SAX_COMMENT</tt> - A comment was just read</li>
  412. <li><tt>MXML_SAX_DATA</tt> - Data (custom, integer, opaque, real, or text) was just read</li>
  413. <li><tt>MXML_SAX_DIRECTIVE</tt> - A processing directive was just read</li>
  414. <li><tt>MXML_SAX_ELEMENT_CLOSE</tt> - A close element was just read (<tt>&lt;/element&gt;</tt>)</li>
  415. <li><tt>MXML_SAX_ELEMENT_OPEN</tt> - An open element was just read (<tt>&lt;element&gt;</tt>)</li>
  416. </ul>
  417. <p>Elements are <em>released</em> after the close element is
  418. processed. All other nodes are released after they are processed.
  419. The SAX callback can <em>retain</em> the node using the <a
  420. href='#mxmlRetain'><tt>mxmlRetain</tt></a> function. For example,
  421. the following SAX callback will retain all nodes, effectively
  422. simulating a normal in-memory load:</p>
  423. <pre>
  424. void
  425. sax_cb(mxml_node_t *node,
  426. mxml_sax_event_t event,
  427. void *data)
  428. {
  429. if (event != MXML_SAX_ELEMENT_CLOSE)
  430. mxmlRetain(node);
  431. }
  432. </pre>
  433. <p>More typically the SAX callback will only retain a small portion
  434. of the document that is needed for post-processing. For example, the
  435. following SAX callback will retain the title and headings in an
  436. XHTML file. It also retains the (parent) elements like <tt>&lt;html&gt;</tt>, <tt>&lt;head&gt;</tt>, and <tt>&lt;body&gt;</tt>, and processing
  437. directives like <tt>&lt;?xml ... ?&gt;</tt> and <tt>&lt;!DOCTYPE ... &gt;</tt>:</p>
  438. <!-- NEED 10 -->
  439. <pre>
  440. void
  441. sax_cb(mxml_node_t *node,
  442. mxml_sax_event_t event,
  443. void *data)
  444. {
  445. if (event == MXML_SAX_ELEMENT_OPEN)
  446. {
  447. /*
  448. * Retain headings and titles...
  449. */
  450. char *name = mxmlGetElement(node);
  451. if (!strcmp(name, "html") ||
  452. !strcmp(name, "head") ||
  453. !strcmp(name, "title") ||
  454. !strcmp(name, "body") ||
  455. !strcmp(name, "h1") ||
  456. !strcmp(name, "h2") ||
  457. !strcmp(name, "h3") ||
  458. !strcmp(name, "h4") ||
  459. !strcmp(name, "h5") ||
  460. !strcmp(name, "h6"))
  461. mxmlRetain(node);
  462. }
  463. else if (event == MXML_SAX_DIRECTIVE)
  464. mxmlRetain(node);
  465. else if (event == MXML_SAX_DATA)
  466. {
  467. if (mxmlGetRefCount(mxmlGetParent(node)) > 1)
  468. {
  469. /*
  470. * If the parent was retained, then retain
  471. * this data node as well.
  472. */
  473. mxmlRetain(node);
  474. }
  475. }
  476. }
  477. </pre>
  478. <p>The resulting skeleton document tree can then be searched just
  479. like one loaded using the <tt>mxmlLoad</tt> functions. For example,
  480. a filter that reads an XHTML document from stdin and then shows the
  481. title and headings in the document would look like:</p>
  482. <pre>
  483. mxml_node_t *doc, *title, *body, *heading;
  484. doc = mxmlSAXLoadFd(NULL, 0,
  485. MXML_TEXT_CALLBACK,
  486. <b>sax_cb</b>, NULL);
  487. title = mxmlFindElement(doc, doc, "title",
  488. NULL, NULL,
  489. MXML_DESCEND);
  490. if (title)
  491. print_children(title);
  492. body = mxmlFindElement(doc, doc, "body",
  493. NULL, NULL,
  494. MXML_DESCEND);
  495. if (body)
  496. {
  497. for (heading = mxmlGetFirstChild(body);
  498. heading;
  499. heading = mxmlGetNextSibling(heading))
  500. print_children(heading);
  501. }
  502. </pre>
  503. </body>
  504. </html>