driver.cxx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // file : examples/roundtrip/driver.cxx
  2. // copyright : not copyrighted - public domain
  3. #include <string>
  4. #include <fstream>
  5. #include <iostream>
  6. #include <xml/parser>
  7. #include <xml/serializer>
  8. using namespace std;
  9. using namespace xml;
  10. int
  11. main (int argc, char* argv[])
  12. {
  13. if (argc != 2)
  14. {
  15. cerr << "usage: " << argv[0] << " <xml-file>" << endl;
  16. return 1;
  17. }
  18. try
  19. {
  20. // Enable stream exceptions so that io failures are reported
  21. // as stream rather than as parsing exceptions.
  22. //
  23. ifstream ifs;
  24. ifs.exceptions (ifstream::badbit | ifstream::failbit);
  25. ifs.open (argv[1], ifstream::in | ifstream::binary);
  26. // Configure the parser to receive attributes as events as well
  27. // as to receive prefix-namespace mappings (namespace declarations
  28. // in XML terminology).
  29. //
  30. parser p (ifs,
  31. argv[1],
  32. parser::receive_default |
  33. parser::receive_attributes_event |
  34. parser::receive_namespace_decls);
  35. // Configure serializer not to perform indentation. Existing
  36. // indentation, if any, will be preserved.
  37. //
  38. serializer s (cout, "out", 0);
  39. for (parser::event_type e (p.next ()); e != parser::eof; e = p.next ())
  40. {
  41. switch (e)
  42. {
  43. case parser::start_element:
  44. {
  45. s.start_element (p.qname ());
  46. break;
  47. }
  48. case parser::end_element:
  49. {
  50. s.end_element ();
  51. break;
  52. }
  53. case parser::start_namespace_decl:
  54. {
  55. s.namespace_decl (p.namespace_ (), p.prefix ());
  56. break;
  57. }
  58. case parser::end_namespace_decl:
  59. {
  60. // There is nothing in XML that indicates the end of namespace
  61. // declaration since it is scope-based.
  62. //
  63. break;
  64. }
  65. case parser::start_attribute:
  66. {
  67. s.start_attribute (p.qname ());
  68. break;
  69. }
  70. case parser::end_attribute:
  71. {
  72. s.end_attribute ();
  73. break;
  74. }
  75. case parser::characters:
  76. {
  77. s.characters (p.value ());
  78. break;
  79. }
  80. case parser::eof:
  81. {
  82. // Handled in the for loop.
  83. //
  84. break;
  85. }
  86. }
  87. }
  88. }
  89. catch (const ios_base::failure&)
  90. {
  91. cerr << "io failure" << endl;
  92. return 1;
  93. }
  94. catch (const xml::exception& e)
  95. {
  96. cerr << e.what () << endl;
  97. return 1;
  98. }
  99. }