xmlwriter.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #ifndef __XMLWRITER_H__
  2. #define __XMLWRITER_H__
  3. #include <iostream>
  4. #include <vector>
  5. #include <string>
  6. /** This class is a class which helps printing formated xml output.
  7. * Example:
  8. * This sequence:
  9. * xml.openTag("world");
  10. * xml.writeAttribute("name", "foo");
  11. * xml.writeTag("bar");
  12. * xml.writeTag("baz");
  13. * xml.writeAttribute("name", "boo");
  14. * xml.writeAttribute("style", "old");
  15. * xml.write("text");
  16. * xml.closeTag("world");
  17. * results in this output:
  18. * <world name="foo">
  19. * <bar/>
  20. * <baz name="boo" style="old">text</baz>
  21. * </world>
  22. */
  23. class XmlWriter {
  24. public:
  25. XmlWriter(std::ostream& out);
  26. ~XmlWriter();
  27. /** Start a xml tag which contains subtags */
  28. void openTag(const char* name);
  29. /** Closes an xml tag with subtags */
  30. void closeTag(const char* name);
  31. void writeTag(const char* name);
  32. template <class T>
  33. void comment(const T& outp)
  34. { // This routine writes just about anything as an XML comment.
  35. newLine();
  36. out << "<!-- " << outp ;
  37. closetag = " -->";
  38. }
  39. template<class T>
  40. void write(const T& text)
  41. {
  42. if (closetag[0]=='>') {
  43. out << ">";
  44. closetag = "";
  45. } else if (closetag[0]=='/') {
  46. out << ">"; // eventually we should place a \n here
  47. closetag = "</";
  48. closetag += lasttag;
  49. closetag += ">";
  50. }
  51. out << text;
  52. }
  53. template<class T>
  54. void writeAttribute(const char* name, T value)
  55. {
  56. out << " " << name << "=\"" << value << "\"";
  57. }
  58. private:
  59. void newLine();
  60. void closeTag();
  61. std::ostream& out;
  62. int indent;
  63. std::string closetag;
  64. std::string lasttag;
  65. std::vector<std::string> sections;
  66. };
  67. #endif