cmXMLWriter.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #ifndef cmXMLWiter_h
  4. #define cmXMLWiter_h
  5. #include "cmConfigure.h" // IWYU pragma: keep
  6. #include "cmXMLSafe.h"
  7. #include <ostream>
  8. #include <stack>
  9. #include <string>
  10. #include <vector>
  11. class cmXMLWriter
  12. {
  13. CM_DISABLE_COPY(cmXMLWriter)
  14. public:
  15. cmXMLWriter(std::ostream& output, std::size_t level = 0);
  16. ~cmXMLWriter();
  17. void StartDocument(const char* encoding = "UTF-8");
  18. void EndDocument();
  19. void StartElement(std::string const& name);
  20. void EndElement();
  21. void BreakAttributes();
  22. template <typename T>
  23. void Attribute(const char* name, T const& value)
  24. {
  25. this->PreAttribute();
  26. this->Output << name << "=\"" << SafeAttribute(value) << '"';
  27. }
  28. void Element(const char* name);
  29. template <typename T>
  30. void Element(std::string const& name, T const& value)
  31. {
  32. this->StartElement(name);
  33. this->Content(value);
  34. this->EndElement();
  35. }
  36. template <typename T>
  37. void Content(T const& content)
  38. {
  39. this->PreContent();
  40. this->Output << SafeContent(content);
  41. }
  42. void Comment(const char* comment);
  43. void CData(std::string const& data);
  44. void Doctype(const char* doctype);
  45. void ProcessingInstruction(const char* target, const char* data);
  46. void FragmentFile(const char* fname);
  47. void SetIndentationElement(std::string const& element);
  48. private:
  49. void ConditionalLineBreak(bool condition, std::size_t indent);
  50. void PreAttribute();
  51. void PreContent();
  52. void CloseStartElement();
  53. private:
  54. static cmXMLSafe SafeAttribute(const char* value)
  55. {
  56. return cmXMLSafe(value);
  57. }
  58. static cmXMLSafe SafeAttribute(std::string const& value)
  59. {
  60. return cmXMLSafe(value);
  61. }
  62. template <typename T>
  63. static T SafeAttribute(T value)
  64. {
  65. return value;
  66. }
  67. static cmXMLSafe SafeContent(const char* value)
  68. {
  69. return cmXMLSafe(value).Quotes(false);
  70. }
  71. static cmXMLSafe SafeContent(std::string const& value)
  72. {
  73. return cmXMLSafe(value).Quotes(false);
  74. }
  75. template <typename T>
  76. static T SafeContent(T value)
  77. {
  78. return value;
  79. }
  80. private:
  81. std::ostream& Output;
  82. std::stack<std::string, std::vector<std::string>> Elements;
  83. std::string IndentationElement;
  84. std::size_t Level;
  85. bool ElementOpen;
  86. bool BreakAttrib;
  87. bool IsContent;
  88. };
  89. #endif