459c220669ae34b470ab058de4a8371bdabdb185
[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), indent(0)
9 {
10 }
11
12 XmlWriter::~XmlWriter()
13 {
14     if(sections.size() > 0) {
15         std::cerr << "WARNING: NOT CLOSED: ";
16         for(std::vector<std::string>::iterator i = sections.begin();
17                 i != sections.end(); ++i)
18             std::cerr << *i << " ";
19         std::cerr << "\n";
20     }
21
22     closeTag();
23 }
24
25 void XmlWriter::openTag(const char* name)
26 {
27     newLine();
28     out << "<" << name;
29     closetag = ">";
30     indent++;
31
32     sections.push_back(name);
33 }
34
35 void XmlWriter::closeTag(const char* name)
36 {
37     if(sections.size() == 0)
38         throw std::runtime_error("got closeSection without prior openSection.");
39
40     const std::string& lastsection = sections.back();
41     if (lastsection != name) {
42         std::ostringstream msg;
43         msg << "mismtach in open/closeSection. Expected '"
44             << lastsection << "' got '" << name << "'";
45         throw std::runtime_error(msg.str());
46     }
47     sections.pop_back();
48
49     indent--;
50     newLine();
51     // XXX: We should check for consistency here
52     out << "</" << name;
53     closetag = ">" ;
54 }
55
56 void XmlWriter::writeTag(const char* name)
57 {
58     newLine();
59     out << "<" << name;
60     closetag = "/>";
61     lasttag = name;
62 }
63
64 void XmlWriter::newLine()
65 {
66     if(closetag != "") {
67         closeTag();
68         for (int i=0;i<indent;i++)
69             out << "\t";
70     }
71 }
72
73 void XmlWriter::closeTag()
74 {
75     if (closetag != "")
76         out << closetag << "\n";
77 }