-Weffc++ cleanup for miniswig
[supertux.git] / tools / miniswig / xmlwriter.cpp
1 #include <config.h>
2
3 #include <stdexcept>
4 #include <sstream>
5 #include "xmlwriter.hpp"
6
7 XmlWriter::XmlWriter(std::ostream& outstream) :
8     out(outstream), 
9     indent(0),
10     closetag(),
11     lasttag(),
12     sections()
13 {
14 }
15
16 XmlWriter::~XmlWriter()
17 {
18     if(sections.size() > 0) {
19         std::cerr << "WARNING: NOT CLOSED: ";
20         for(std::vector<std::string>::iterator i = sections.begin();
21                 i != sections.end(); ++i)
22             std::cerr << *i << " ";
23         std::cerr << "\n";
24     }
25
26     closeTag();
27 }
28
29 void XmlWriter::openTag(const char* name)
30 {
31     newLine();
32     out << "<" << name;
33     closetag = ">";
34     indent++;
35
36     sections.push_back(name);
37 }
38
39 void XmlWriter::closeTag(const char* name)
40 {
41     if(sections.size() == 0)
42         throw std::runtime_error("got closeSection without prior openSection.");
43
44     const std::string& lastsection = sections.back();
45     if (lastsection != name) {
46         std::ostringstream msg;
47         msg << "mismatch in open/closeSection. Expected '"
48             << lastsection << "' got '" << name << "'";
49         throw std::runtime_error(msg.str());
50     }
51     sections.pop_back();
52
53     indent--;
54     newLine();
55     // XXX: We should check for consistency here
56     out << "</" << name;
57     closetag = ">" ;
58 }
59
60 void XmlWriter::writeTag(const char* name)
61 {
62     newLine();
63     out << "<" << name;
64     closetag = "/>";
65     lasttag = name;
66 }
67
68 void XmlWriter::newLine()
69 {
70     if(closetag != "") {
71         closeTag();
72         for (int i=0;i<indent;i++)
73             out << "\t";
74     }
75 }
76
77 void XmlWriter::closeTag()
78 {
79     if (closetag != "")
80         out << closetag << "\n";
81 }