XmlWriter.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2016, University of Freiburg,
  2. // Chair of Algorithms and Data Structures.
  3. // Authors: Patrick Brosi <brosi@informatik.uni-freiburg.de>
  4. #ifndef UTIL_XML_XMLWRITER_H_
  5. #define UTIL_XML_XMLWRITER_H_
  6. #include <map>
  7. #include <ostream>
  8. #include <stack>
  9. #include <string>
  10. namespace util {
  11. namespace xml {
  12. class XmlWriterException : public std::exception {
  13. public:
  14. XmlWriterException(std::string msg) : _msg(msg) {}
  15. ~XmlWriterException() throw() {}
  16. virtual const char* what() const throw() { return _msg.c_str(); };
  17. private:
  18. std::string _msg;
  19. };
  20. // simple XML writer class without much overhead
  21. class XmlWriter {
  22. public:
  23. explicit XmlWriter(std::ostream* out);
  24. XmlWriter(std::ostream* out, bool pretty);
  25. XmlWriter(std::ostream* out, bool pretty, size_t indent);
  26. ~XmlWriter(){};
  27. // open tag without attributes
  28. void openTag(const std::string& tag);
  29. // open tag with single attribute (for convenience...)
  30. void openTag(const std::string& tag, const std::string& key,
  31. const std::string& val);
  32. // open tag with attribute list
  33. void openTag(const std::string& tag,
  34. const std::map<std::string, std::string>& attrs);
  35. // open comment
  36. void openComment();
  37. // write text
  38. void writeText(const std::string& text);
  39. // close tag
  40. void closeTag();
  41. // close all open tags, essentially closing the document
  42. void closeTags();
  43. private:
  44. enum XML_NODE_T { TAG, TEXT, COMMENT };
  45. struct XmlNode {
  46. XmlNode(XML_NODE_T t, const std::string& pload, bool hanging)
  47. : t(t), pload(pload), hanging(hanging) {}
  48. XML_NODE_T t;
  49. std::string pload;
  50. bool hanging;
  51. };
  52. std::ostream* _out;
  53. std::stack<XmlNode> _nstack;
  54. bool _pretty;
  55. size_t _indent;
  56. // handles indentation
  57. void doIndent();
  58. // close "hanging" tags
  59. void closeHanging();
  60. // pushes XML escaped text to stream
  61. void putEsced(std::ostream* out, const std::string& str, char quot);
  62. // checks tag names for validiy
  63. void checkTagName(const std::string& str) const;
  64. };
  65. } // namespace xml
  66. } // namespace util
  67. #endif // UTIL_XML_XMLWRITER_H_